熟悉Python的各种基础小算法

网上有一个Python100小例子的栏目,里面代码良莠不齐,于是下面就自己实现了其中的一些案例。

01.py

# coding:utf-8
import sys

reload(sys)
sys.setdefaultencoding('utf8')
#    __author__ = '郭 璞'
#    __date__ = '2016/8/24'
#    __Desc__ = 

'''
题目:有1、2、3、4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少?
程序分析:可填在百位、十位、个位的数字都是1、2、3、4。组成所有的排列后再去 掉不满足条件的排列。
'''

source = [1,2,3,4]

for i in range(len(source)):
    for j in range(len(source)):
        for k in range(len(source)):
            if source[i]!=source[j] and source[i]!=source[k] and source[j]!=source[k]:
                print source[i],source[j],source[k]

02.py

# coding:utf-8
import sys

reload(sys)
sys.setdefaultencoding('utf8')
#    __author__ = '郭 璞'
#    __date__ = '2016/8/24'
#    __Desc__ =

'''
题目:企业发放的奖金根据利润提成。利润(I)低于或等于10万元时,奖金可提10%;
利润高于10万元,低于20万元时,低于10万元的部分按10%提成,高于10万元的部分,可可提成7.5%;
20万到40万之间时,高于20万元的部分,可提成5%;40万到60万之间时高于40万元的部分,可提成3%;
60万到100万之间时,高于60万元的部分,可提成1.5%,
高于100万元时,超过100万元的部分按1%提成,从键盘输入当月利润I,求应发放奖金总数?
'''

money = int(raw_input('Please input the money:\n'))

money_list = [1000000,600000,400000,200000,100000,0]
percent_list = [0.01,0.025,0.03,0.05,0.075,0.1]

scholarship = 0

for index in range(0,6):
    if money > money_list[index]:
        scholarship +=(money-money_list[index])*percent_list[index]
        print (money-money_list[index])*percent_list[index]
        money = money_list[index]

print scholarship

03.py

# coding:utf-8
import sys

reload(sys)
sys.setdefaultencoding('utf8')
#    __author__ = '郭 璞'
#    __date__ = '2016/8/24'
#    __Desc__ = 一个整数,它加上100和加上268后都是一个完全平方数,请问该数是多少?
import math

for i in range(1,10000):
    x = int(math.sqrt(i+100))
    y = int(math.sqrt(i+268))
    if (x*x == i + 100) and (y*y == i+268):
        print i

04.py

# coding:utf-8
import sys

reload(sys)
sys.setdefaultencoding('utf8')
#    __author__ = '郭 璞'
#    __date__ = '2016/8/24'
#    __Desc__ = 输入某年某月某日,判断这一天是这一年的第几天?

year = int(raw_input('请输入年份:\n'))
month = int(raw_input('请输入月份:\n'))
day = int(raw_input('请输入日期:\n'))

days = [0,31,59,90,120,151,181,212,243,273,304,334]
result = 0
if 0< month <= 12:
    result = days[month]
else:
    result = 0

result += day

if year%400==0 or (year%4==0 and year%100!=0):

    if month >2 : result +=1

print '%d-%d-%d是今年的第%d天!'%(year,month,day,result)

05.py

# coding:utf-8
import sys
reload(sys)

sys.setdefaultencoding('utf8')
#    __author__ = '郭 璞'
#    __date__ = '2016/8/26'
#    __Desc__ = 输入三个整数x,y,z,请把这三个数由小到大输出。

# ls = []
# for iten in range(0,3):
#     ls.append(int(raw_input('请输入一个数字:\n')))
# ls.sort()

ls = [1,3,6,2,4,8,7,9,0]
target = []
for item in ls:
    target.append(item)
    target.sort()
    print target

print '输入的数据由大到小的顺序为:\n',target

06.py

# coding:utf-8
import sys

reload(sys)
sys.setdefaultencoding('utf8')
#    __author__ = '郭 璞'
#    __date__ = '2016/8/26'
#    __Desc__ = 输出9*9乘法口诀表。

for x in range(1,10):
    for y in range(1,x+1):
        # 原来实现Python2.7print的输出不换行的关键在于句末的一个小逗号啊!!!
        print "%d*%d=%d\t"%(x,y,x*y),
    print '\n'


07.py

# coding:utf-8
import sys

reload(sys)
sys.setdefaultencoding('utf8')
#    __author__ = '郭 璞'
#    __date__ = '2016/8/26'
#    __Desc__ = 暂停一秒输出。

import time

print '一秒后将会处处另一句话!'
time.sleep(1)
print '这就是一秒后的那句话!'

08.py

# coding:utf-8
import sys

reload(sys)
sys.setdefaultencoding('utf8')
#    __author__ = '郭 璞'
#    __date__ = '2016/8/26'
#    __Desc__ = 古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,
# 小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?

ls = [1,1]
for item in range(0,6):
    top = ls[-1]
    sec_top = ls[-2]
    ls.append((top+sec_top))
    ls.sort()

for item in range(len(ls)):
    print '第%d个月,兔子数量为:%d'%(item+1,ls[item])

09.py

# coding:utf-8
import sys

reload(sys)
sys.setdefaultencoding('utf8')
#    __author__ = '郭 璞'
#    __date__ = '2016/8/26'
#    __Desc__ = 判断101-200之间有多少个素数,并输出所有素数。

def is_sushu(number):
    for item in range(2,number):
        if number%item==0:
            return False
    return True

if __name__=="__main__":
    for i in range(101,201):
        if is_sushu(i):
            print i


10.py

# coding:utf-8
import sys

reload(sys)
sys.setdefaultencoding('utf8')
#    __author__ = '郭 璞'
#    __date__ = '2016/8/26'
#    __Desc__ = 打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,
# 其各位数字立方和等于该数本身。例如:153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。

# 返回给定数字的水仙花计数值
def return_water_flower_number(number):
    ls = []
    i = 0
    while True:
        i = number %10
        ls.append(i)
        number = (number -i)/10
        if number ==0:
            break
    sum_sum = 0
    for item in ls:
        sum_sum+=int(item)**3
    return sum_sum

if __name__=="__main__":
    for i in range(1,10000):
        if return_water_flower_number(i)==i:
            print i

11.py

# coding:utf-8
import sys

reload(sys)
sys.setdefaultencoding('utf8')
#    __author__ = '郭 璞'
#    __date__ = '2016/8/26'
#    __Desc__ = 将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。

# 呵呵,这段代码我都佩服我自己了,竟然真的可以这么愉快的运行下去
def fenjie(number):
    ls = []
    i = 2
    while True:
        if number%i==0:
            ls.append(i)
            number = number/i
            if number / i == 1:
                ls.append(number)
                break
        else:
            i+=1
        if number/i ==1:
            ls.append(number)
            break

    return ls

if __name__=="__main__":
    num = int(raw_input('请输入一个数字:\n'))
    print "%d的所有质因数是:%d=" % (num,num),
    for item in fenjie(num):
        print item,'*',

12.py

# coding:utf-8
import sys

reload(sys)
sys.setdefaultencoding('utf8')
#    __author__ = '郭 璞'
#    __date__ = '2016/8/26'
#    __Desc__ = 求s=a+aa+aaa+aaaa+aa...a的值,其中a是一个数字。例如2+22+222+2222+22222(此时共有5个数相加),几个数相加有键盘控制。

def retravel(number,times):
    result = 0
    tag = number
    for index in range(1,times+1):
        result += number
        number = number*10+tag

    return result

if __name__=="__main__":
    number = int(raw_input('请输入0-9之间的一个数字:\n'))
    times = int(raw_input('请输入要循环的次数:\n'))
    print '结果是:',retravel(number,times)

13.py

# coding:utf-8
import sys

reload(sys)
sys.setdefaultencoding('utf8')
#    __author__ = '郭 璞'
#    __date__ = '2016/8/26'
#    __Desc__ = 一个数如果恰好等于它的因子之和,这个数就称为"完数"。
# 例如6=1+2+3.编程找出1000以内的所有完数。

def is_full_number(number):
    ls = []
    i = 1
    for i in range(1,number):
        if number %i==0:
            ls.append(i)
            if i+1== number:
                break
        else:
            continue
    summary = 0
    for i in ls:
        summary +=i
    if summary == number :
        return True
    else:
        return False

if __name__ == "__main__":
    for i in range(1,10000):
        if is_full_number(i):
            print i

14.py

# coding:utf-8
import sys

reload(sys)
sys.setdefaultencoding('utf8')
#    __author__ = '郭 璞'
#    __date__ = '2016/8/26'
#    __Desc__ = 一球从100米高度*落下,每次落地后反跳回原高度的一半;
# 再落下,求它在第10次落地时,共经过多少米?第10次反弹多高?

def get_total_height(height,times):
    total_height = float(height)
    temp_height = 0.0
    for i in range(1,times):
        height = float(height) /2
        temp_height = height
        total_height+=2*height
    return (total_height,temp_height)

if __name__=="__main__":
    height = 100.0
    times = 10
    print "所求高度和为:%d,最后一次落地弹起高度为:%d"%get_total_height(height,times)

15.py

# coding:utf-8
import sys

reload(sys)
sys.setdefaultencoding('utf8')
#    __author__ = '郭 璞'
#    __date__ = '2016/8/26'
#    __Desc__ = 猴子吃桃问题:猴子第一天摘下若干个桃子,当即吃了一半,还不瘾,又多吃了一个第二天早上又将剩下的桃子吃掉一半,又多吃了一个。
# 以后每天早上都吃了前一天剩下的一半零一个。到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘了多少。

def get_total_peaches(day):
    total_peaches = 0
    if day == 10:
        total_peaches = 1
    else:
        total_peaches = (get_total_peaches(day+1)+1)*2
    return total_peaches

print 'total peaches is:%d'%get_total_peaches(1)

16.py

暂留

# coding:utf-8
import sys

reload(sys)
sys.setdefaultencoding('utf8')
#    __author__ = '郭 璞'
#    __date__ = '2016/8/26'
#    __Desc__ = 利用递归函数调用方式,将所输入的5个字符,以相反顺序打印出来。

def append(char):
    pass

17.py

# coding:utf-8
import sys

reload(sys)
sys.setdefaultencoding('utf8')
#    __author__ = '郭 璞'
#    __date__ = '2016/8/31'
#    __Desc__ = 一个5位数,判断它是不是回文数。即12321是回文数,个位与万位相同,十位与千位相同。

def isHuiWen(number):
    arr =  str(number)
    start = 0
    end = len(arr)-1
    flag = (end-start)/2
    while start <=end :
        print arr[start],arr[end]
        if arr[start]==arr[end]:
            start +=1
            end-=1
        else:
            return False
    return True

if __name__=="__main__":
    result = isHuiWen(123321)
    if result:
        print "Yes"
    else:
        print "NO!"

18.py

# coding:utf-8
import sys

reload(sys)
sys.setdefaultencoding('utf8')
#    __author__ = '郭 璞'
#    __date__ = '2016/8/31'
#    __Desc__ = 按相反的顺序输出列表的值。

def reverse_print(list):
    end = len(list)-1
    while end>=0:
        print list[end]
        end-=1

# 使用系统的内建方法,分片技术
def reverse_slice(list):
    for item in list[::-1]:
        print item

def reverse(list=[]):
    reverse_list = []
    end = len(list)-1
    while end>=0:
        reverse_list.append(list[end])
        end-=1
    return reverse_list

if __name__ == "__main__":
    list = [1,2,3,4,5,6,7,8,9]
    # reverse_print(list)
    # result = reverse(list)
    # for item in result:
    #     print item,
    reverse_slice(list)

19.py

# coding:utf-8
import sys

reload(sys)
sys.setdefaultencoding('utf8')
#    __author__ = '郭 璞'
#    __date__ = '2016/8/31'
#    __Desc__ = 按逗号分隔列表。

def devide_list(list):
    # 这里的str(item)必须添加,否则会导致字符串拼接的类型不匹配的异常
    return ','.join(str(item) for item in list)

if __name__ =="__main__":
    list = [1,2,3,4,5,6,7]
    print devide_list(list)

20.py

# coding:utf-8
import sys

reload(sys)
sys.setdefaultencoding('utf8')
#    __author__ = '郭 璞'
#    __date__ = '2016/8/31'
#    __Desc__ = 文本颜色设置

# 类似于shell形式的编写,可以改变终端下字体的颜色,达到一个很好的变成体验的效果
class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'
print bcolors.OKGREEN + "警告的颜色字体?"+bcolors.UNDERLINE+"第二个颜色显示"

21.py

# coding:utf-8
import sys

reload(sys)
sys.setdefaultencoding('utf8')
#    __author__ = '郭 璞'
#    __date__ = '2016/8/31'
#    __Desc__ = 将一个数组逆序输出。

def reverse_array(arr):
    left = 0
    right = len(arr)-1
    while left <=right:
        temp = arr[left]
        arr[left]= arr[right]
        arr[right]= temp

        left+=1
        right-=1
    return arr

if __name__=="__main__":
    arr = ['1',2,3,'Hello']
    arr = reverse_array(arr)
    print arr

22.py

# coding:utf-8
import sys

reload(sys)
sys.setdefaultencoding('utf8')
#    __author__ = '郭 璞'
#    __date__ = '2016/9/1'
#    __Desc__ = 交换两个数的值
# 其实原理都是一样的,只不过Python可以借助于tuple,元组的形式来一次性的返回多个值
# 相对于其他编程语言而言,这真的很方便

def change(a,b):
    temp = a
    a = b
    b = temp
    return a,b

def exchange(a,b):
    a,b = b,a
    return a,b

if __name__=="__main__":
    a ,b = 1,2
    print '原来的值:%d---%d'%(a,b)
    a,b = exchange(a,b)
    print '值交换后:%d---%d' % (a, b)
    c,d = change(a,b)
    print '值交换后:%d---%d' % (a, b)
    print type(change(a,b))

23.py

# coding:utf-8
import sys

reload(sys)
sys.setdefaultencoding('utf8')
#    __author__ = '郭 璞'
#    __date__ = '2016/9/1'
#    __Desc__ = 使用lambda来创建匿名函数。关键在于lambda表达式紧跟参数,以分号分隔后的表达式只能为算术逻辑表达式,不能有判断等语句

MAX = lambda x,y: (x>y)*x + (x<y)*y
MIN = lambda x,y: (x<y)*x + (x>y)*y
SUM = lambda x,y: x+y
SUB = lambda x,y: (x>y)*(x) + (x<y)*(y-x)
MUT = lambda x,y:(x!=0)*(x*y) or 0
DIV = lambda x,y: (x*y!=0)*(((float)(x)/(float)(y))) or "除数不能为0!"

if __name__=="__main__":
    x = 10
    y = 100
    print "MAX:",MAX(x,y)
    print "MIN:",MIN(x,y)
    print "SUM:",SUM(x,y)
    print "SUB:",SUB(x,y)
    print "SUB:" , SUB(y, x)
    print "MUT:",MUT(x,y)
    print "DIV:",DIV(x,y)
    print "DIV:" , DIV(y, x)

24.py

# coding:utf-8
import sys

reload(sys)
sys.setdefaultencoding('utf8')
#    __author__ = '郭 璞'
#    __date__ = '2016/9/1'
#    __Desc__ = 输出一个随机数。

from random import *

# 返回的是整数
def rand_arrange_in(a, b):
    return randint(a, b)

# 返回的不是整数
def rand_uniform(a, b):
    return uniform(a, b)

if __name__ == "__main__":
    start = 10
    end = 28
    print "---------------单个数字-------------------------"
    print "random int:%d" % rand_arrange_in(start, end)
    print "random uniform:%d" % rand_uniform(start, end)
    print "---------------多个数字-------------------------"
    print "random int:\n"
    for item in range(0, 10):
        print rand_arrange_in(start, end),
    print "\nrandom uniform:"
    for item in range(0, 10):
        print rand_uniform(start, end),

25.py

# coding:utf-8
import sys

reload(sys)
sys.setdefaultencoding('utf8')
#    __author__ = '郭 璞'
#    __date__ = '2016/9/1'
#    __Desc__ = 取一个整数a从右端开始的4〜7位。
# 原文的例子是不正确的
"""if __name__ == '__main__':
    a = int(raw_input('input a number:\n'))
    b = a >> 4
    c = ~(~0 << 4)
    d = b & c
    print '%o\t%o' %(a,d)
"""

# 将所给的数字分解,取后四位
def split1(number):
    number = str(number)
    result = []
    length = len(number)-1
    index = length-3
    while index<=length:
        result.append(number[index])
        index+=1
    return ''.join(char for char in result)

def split2(number):
    # if type(number) == 'str':
    #     return number[0]
    # else:
        return int(number) % (10000)

if __name__ == "__main__":
    number = 1234567890
    print split1(number)

    print split2(number)
    str_num = str(1234567)
    print split2(str_num)

26.py

# coding:utf-8
import sys

reload(sys)
sys.setdefaultencoding('utf8')
#    __author__ = '郭 璞'
#    __date__ = '2016/9/1'
#    __Desc__ = 使用Tkinter画同心圆

def circle(width=800,height=600,bg='green'):
    from Tkinter import *
    # 确定画布信息
    canvas = Canvas(width=width,height=height,bg=bg)
    canvas.pack(expand=YES,fill=BOTH)

    k = 1
    j = 1
    # 确定圆的个数
    for index in range(0,32):
        # 画圆需要提供的参数信息
        canvas.create_oval(width/2-k,height/2-k,width/2+k,height/2+k,width=1)
        k+=j
        j+=0.5
    mainloop()

if __name__ =="__main__":
    circle(1080,720,'purple')

27.py

# coding:utf-8
import sys

reload(sys)
sys.setdefaultencoding('utf8')
#    __author__ = '郭 璞'
#    __date__ = '2016/9/1'
#    __Desc__ = 打印出杨辉三角形(要求打印出10行)。  
# 本例为原题答案,非原创

if __name__ == '__main__':
    a = []
    for i in range(10):
        a.append([])
        for j in range(10):
            a[i].append(0)
    for i in range(10):
        a[i][0] = 1
        a[i][i] = 1
    for i in range(2,10):
        for j in range(1,i):
            a[i][j] = a[i - 1][j-1] + a[i - 1][j]
    from sys import stdout
    for i in range(10):
        for j in range(i + 1):
            stdout.write(str(a[i][j]))
            stdout.write(' ')
        print

28.py

# coding:utf-8
import sys

reload(sys)
sys.setdefaultencoding('utf8')
#    __author__ = '郭 璞'
#    __date__ = '2016/9/1'
#    __Desc__ = 查找字符串。  

# 返回第一次出现该子字符串的位置,从零开始计数
def find(full_str,sub_str):
    return full_str.find(sub_str)

# 采用自定义的"哈希算法",其实就是朴素的KMP算法实现。
# 本来是想把full_str改装成多个长度和sub_str的字符串相等长度的数组来计算其哈希和,相等的话作进一步的判断,但是Python实现起来略显复杂
def kmp(full_str,sub_str):
    sub_length = len(sub_str)
    full_length= len(full_str)

    for item in range(0,full_length-sub_length):
        # 设置 判断令牌
        flag = False
        # 对每一个子串进行验证
        for validate in range(0,sub_length):
            if full_str[item+validate]==sub_str[validate]:
                flag=True
            else:
                flag = False
            # 如果令牌为真,且长度刚好验证到sub_str的全部长度
            if flag and validate==sub_length-1:
                return item

if __name__=="__main__":
    full = "I am a handsome boy"
    sub = " a"
    print find(full,sub)
    print kmp(full,sub)

29.py

# coding:utf-8
import sys

reload(sys)
sys.setdefaultencoding('utf8')
#    __author__ = '郭 璞'
#    __date__ = '2016/9/1'
#    __Desc__ = 输入数组,最大的与第一个元素交换,最小的与最后一个元素交换,输出数组。

#
def swap(arr):
    max_index = 0
    min_index = 0
    max = arr[0]
    min = arr[0]
    for item in range(len(arr)):
        if max<arr[item]:
            max = arr[item]
            max_index = item
        if min > arr[item]:
            min = arr[item]
            min_index = item
    max,arr[0] = arr[0],max
    min,arr[len(arr)-1] = arr[len(arr)-1],min
    return arr

if __name__ =="__main__":
    arr = [1,2,3,4,5,6,7,8,9]
    print'交换前:',arr
    print '交换后:',swap(arr)

30.py

# coding:utf-8
import sys

reload(sys)
sys.setdefaultencoding('utf8')
#    __author__ = '郭 璞'
#    __date__ = '2016/9/1'
#    __Desc__ = 有n个整数,使其前面各数顺序向后移m个位置,最后m个数变成最前面的m个数

# 将后面的M个数字全部转到前面,且顺序保持不变。利用了列表的分片操作
def shift_right(ls,number):
    temp = ls[len(ls)-number:]
    ls = ls[0:len(ls)-number]
    for item in range(0,len(ls)):
        temp.append(ls[item])
    return temp

if __name__ == '__main__':
    ls = [1,2,3,4,5,6,7]
    print shift_right(ls,3)

31.py

# coding:utf-8
import sys

reload(sys)
sys.setdefaultencoding('utf8')
#    __author__ = '郭 璞'
#    __date__ = '2016/9/1'
#    __Desc__ = 809*??=800*??+9*??+1 其中??代表的两位数,
# 8*??的结果为两位数,9*??的结果为3位数。求??代表的两位数,及809*??后的结果。

if __name__ == '__main__':
    a = 809
    for i in range(10, 100):
        b = i * a + 1
        if b >= 1000 and b <= 10000 and 8 * i < 100 and 9 * i >= 100:
            print b, '/', i, ' = 809 * ', i, ' + ', b % i

32.py

# coding:utf-8
import sys

reload(sys)
sys.setdefaultencoding('utf8')
#    __author__ = '郭 璞'
#    __date__ = '2016/9/1'
#    __Desc__ = 某个公司采用公用电话传递数据,数据是四位的整数,
# 在传递过程中是加密的,加密规则如下:每位数字都加上5,
# 然后用和除以10的余数代替该数字,再将第一位和第四位交换,
# 第二位和第三位交换。

def decode(number):
    ge = number%10
    shi = (number%100-ge)/10
    bai = (number%1000-10*shi-ge)/100
    qian = number/1000
    ge,shi,bai,qian= (ge+5)%10,(shi+5)%10,(bai+5)%10,(qian+5)%10
    qian,ge = ge,qian
    bai,shi = shi ,bai
    return qian*1000+bai*100+shi*10+ge

if __name__ == '__main__':
    number = 1221
    print decode(number)

33.py

# coding:utf-8
import sys

reload(sys)
sys.setdefaultencoding('utf8')
#    __author__ = '郭 璞'
#    __date__ = '2016/9/1'
#    __Desc__ = 列表转换为字典。

# 系统内置的实现,也即是一个列表对应一个字典项,所以长度当且仅当为2!!!
def build_in(ls_key,ls_value):

    # 列表项中的元素数据至多为2两个
    # print dict([ls_value, ls_key])
    return dict([ls_key,ls_value])

# 自定义的实现,key集合匹配value集合实现列表转字典
def my_translator(ls_key,ls_value):
    if len(ls_key)!=len(ls_value):
        print "键值对的长度不匹配!"
        exit(0)
    dict = {}
    for item in range(len(ls_key)):
        dict[ls_key[item]]=ls_value[item]
    return dict

if __name__ == '__main__':
    ls_key = ['x', 'y']
    ls_value = [1, 2]
    print build_in(ls_key,ls_value)
    ls_key.append('z')
    ls_value.append(3)
    print my_translator(ls_key,ls_value)

总结

案例很简单,但是确实是编程思想的深刻的体现,做完这些小例子,方能感受到基础知识的重要性。

千万不要以为某些东西简单而一掠而过,否则还是会花费更多时间!

上一篇:6389. 【NOIP2019模拟2019.10.26】小w学图论


下一篇:bzoj1055 ||P4290 [HAOI2008]玩具取名