profit=int(input('Show me the money: ')) money = [100000,100000,200000,200000,400000] rates = [0.1,0.075,0.05,0.03,0.015,0.01] bonus=0 for i in range(len(money)): if profit <= money[i]: bonus += profit*rates[i] profit = 0 else: bonus += money[i]*rates[i] profit -= money[i] bonus += profit*rates[-1] print(bonus) ``` 解法2: ```py profit=int(input('Show me the money: ')) arr = [1000000,600000,400000,200000,100000,0] rat = [0.01,0.015,0.03,0.05,0.075,0.1] r = 0 for idx in range(0,6): if profit>arr[idx]: r+=(profit-arr[idx])*rat[idx] profit=arr[idx] print (r)
实例: 完全平方数:
一个整数,它加上100后是一个完全平方数,再加上168又是一个完 全平方数,请问该数是多少?
程序分析:
假设该数为 x。 1、则:x + 100 = n2, x + 100 + 168 = m2 2、计算等式:m2 - n2 = (m + n)(m - n) = 168 3、设置: m + n = i,m - n = j,i * j =168,i 和 j 至少一个是偶数 4、可得: m = (i + j) / 2, n = (i - j) / 2,i 和 j 要么都是偶数,要么都是奇数。 5、从 3 和 4 推导可知道,i 与 j 均是大于等于 2 的偶数。 6、由于 i * j = 168, j>=2,则 1 < i < 168 / 2 + 1。 7、下来将 i 的所有数字循环计算即可。
当然直接用最朴素的方法即可解决本问题
1 2 3 4 5
i = -99# 1是最小的平方数 while i<10000: iif (i+100)**0.5==int((i+100)**0.5)and (i+100+168)**0.5==int((i+100+168)**0.5): print (i) i=i+1
修订版:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#这一步是找到相邻两个数的平方差大于等于168的数n n=0 while (n+1)**2-n*n<=168: n+=1
for i in range((n+1)**2): if i**0.5==int(i**0.5)and (i+168)**0.5==int((i+168)**0.5): print(i-100) ## 源代码 for i in range(1,n): if168 % i == 0: j = 168 / i if i > j and (i + j) % 2 == 0and (i - j) % 2 == 0 : m = (i + j) / 2 n = (i - j) / 2 x = n * n - 100 print(int(x))
实例004: 这天第几天
输入某年某月某日,判断这一天是这一年的第几天?
程序分析 特殊情况,闰年时需考虑二月多加一天:
1 2 3 4 5 6 7 8 9 10 11 12
defisLeapYear(y): return (y%400==0or (y%4==0and y%100!=0)) DayOfMonth=[0,31,28,31,30,31,30,31,31,30,31,30] res=0 year=int(input('Year:')) month=int(input('Month:')) day=int(input('day:')) if isLeapYear(year): DayOfMonth[2]+=1 for i in range(1,month): res+=DayOfMonth[i] print(res+day)
实例005:三数排序
输入三个整数x,y,z,请把这三个数由小到大输出。
练练手可以自己写一个排序算法,偷懒就直接调用函数
1 2 3 4 5 6 7 8 9 10 11
num = [] for i in range(3): x = int (input('the %d is : '%(i+1))) num.append(x) defsort1(num): for i in range(len(num)): for j in range(i,len(num)): if(num[i]>num[j]): num[i],num[j]=num[j],num[i] return num print(sort1(num))
for i in range(1,month): month_1,month_2,month_elder=month_elder+month_2,month_1,month_elder+month_2 print('第%d个月共'%(i+1),month_1+month_2+month_elder,'对兔子') print('其中1月兔:',month_1) print('其中2月兔:',month_2) print('其中成年兔:',month_elder)
defrabbit(n): if n<= 2: return1 else : return rabbit(n-1)+rabbit(n-2)
print(rabbit(month))
defrabbit(n): if n<= 2: return1 else : return rabbit(n-1)+rabbit(n-2)
whileTrue: if target == 1: break for i in range(2, target+1): if target % i == 0: print(i, end='') if target != i: print("*", end='') target = int(target/i) break
high = 100.0 tim = 10 total = 0 for i in range(tim): if i == 0: total += high else : total += high *2 high /= 2 print ("high= {},total = {}".format(high,total))
a=set(['x','y','z']) b=set(['x','y','z']) c=set(['x','y','z']) c-=set(('x','z')) a-=set('x') for i in a: for j in b: for k in c: if len(set((i,j,k)))==3: print('a:%s,b:%s,c:%s'%(i,j,k))
画菱形
1 2 3 4 5 6 7 8
打印出如下图案 * *** ***** ******* ***** *** *
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
from sys import stdout defdraw(n): for i in range(n): for j in range(n-i): stdout.write(' ') for k in range(2*i+1): stdout.write('*') stdout.write('\n') for i in range(n-1,0,-1): for j in range(n+1-i): stdout.write(' ') for k in range(2*i-1): stdout.write('*') stdout.write('\n') draw(4)
x = int(input("请输入一个数:\n")) a = x // 10000 b = x % 10000 // 1000 c = x % 1000 // 100 d = x % 100 // 10 e = x % 10 if a != 0: print ("5 位数:",e,d,c,b,a) elif b != 0: print ("4 位数:",e,d,c,b,) elif c != 0: print ("3 位数:",e,d,c) elif d != 0: print ("2 位数:",e,d) else: print ("1 位数:",e) # 还是字符串比较简单 s = str(x) n = len(s) print(str(n)+" 位数 逆序为:"+ s[::-1])
实例030:回文数
一个5位数,判断它是不是回文数。即12321是回文数,个位与万位相同,十位与千位相同。
1 2 3 4 5
n=input("随便你输入啥啦:") if n == (n[::-1]): print (n+"是回文数") else: print (n+"不是回文数")
实例031:字母识词
请输入星期几的第一个字母来判断一下是星期几,如果第一个字母一样,则继续判断第二个字母。
可以用条件语句或者switch解决.本题尝试用字典来写一下
1 2 3 4 5 6 7 8 9 10 11 12 13 14
weekT={'h':'Thursday', 'u':'Tuesday'} weekS={'a':'Saturday', 'u':'Sunday'} week={'t':weekT, 's':weekS, 'm':'Monday', 'w':'Wensday', 'f':'Friday'} a=week[input('请输入第一位字母:').lower()] if a==weekT or a==weekS: print(a[input('请输入第二位字母:').lower()]) else: print(a)
实例032:反向输出II
按相反的顺序输出列表的值。
1 2 3 4 5 6
a = ['one', 'two', 'three'] print(a[::-1]) # for i in range(len(a)): a[i]=a[i][::-1] print(a[::-1])
实例033:列表转字符串
按逗号分隔列表。
1 2
L = [1,2,3,4,5] print(','.join(str(n) for n in L))
实例034:调用函数
练习函数调用。
1 2 3 4 5 6 7 8
defhello(): print('Hello World!') defhelloAgain(): for i in range(2): hello()
lo=int(input('下限:')) hi=int(input('上限:')) for i in range(lo,hi+1): if i > 1: for j in range(2,i): if (i % j) == 0: break else: print(i)
示例037:排序
对10个数进行排序。
跟第五题一样
1 2 3 4 5 6 7 8 9 10 11
num = [] for i in range(3): x = int (input('the %d is : '%(i+1))) num.append(x) defsort1(num): for i in range(len(num)): for j in range(i,len(num)): if(num[i]>num[j]): num[i],num[j]=num[j],num[i] return num print(sort1(num))
实例038: 矩阵对角线之和
一个3*3矩阵主对角线元素之和。
1 2 3 4 5 6 7 8
mat=[[1,2,3], [3,4,5], [4,5,6] ] res=0 for i in range(len(mat)): res+=mat[i][i] print(res)
实例039:有序列表插入元素
有一个已经排好序的数组。现输入一个数,要求按原来的规律将它插入数组中。
程序分析:先加在最后,然后判断是否比前一个大
1 2 3 4 5 6 7 8 9 10 11
ls = [1,10,100,1000,10000,20000] ln = len(ls) print (ls) n = int(input('insert a number:')) ls.append(n) while ln: if ls[ln] < ls[ln-1]: ls [ln-1],ls[ln] = ls[ln],ls[ln-1] ln-=1 else : break print(ls)
实例040:逆序列表
将一个数组逆序输出。
程序分析 依次交换位置,或者直接调用reverse方法。
1 2 3 4 5 6 7 8 9 10 11
lis=[1,10,100,1000,10000,100000] for i in range(int(len(lis)/2)): lis[i],lis[len(lis)-1-i]=lis[len(lis)-1-i],lis[i] print('第一种实现:') print(lis)
i=0 n=0 defdummy(): i=0 print(i) i+=1 defdummy2(): global n print(n) n+=1 print('函数内部的同名变量') for j in range(20): print(i) dummy() i+=1 print('global声明同名变量') for k in range(20): print(n) dummy2() n+=10
实例043:作用域、类的方法与变量
模仿静态变量(static)另一案例。
程序分析 综合实例041和实例042。
1 2 3 4 5 6 7 8 9 10 11
classdumy: num = 1 defNum(self): print('class dumy num:',self.num) print('global num:',num) self.num+=1 n = dumy() num = 1 for i in range(5): num*=10 n.Num()
实例044:矩阵相加
计算两个矩阵相加。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
X = [[12,7,3], [4 ,5,6], [7 ,8,9]] Y = [[5,8,1], [6,7,3], [4,5,9]] defadd(X,Y): if len(X)==len(Y) and len(X[0])==len(Y[0]): for i in range(len(X)): for j in range(len(X[0])): X[i][j]+=Y[i][j] print(X) return X else : print('wrong!!!') return
TODO
拓展:矩阵相乘
1 2
实例045:求和
统计 1 到 100 之和。
1 2 3 4
res=0 for i in range(1,101): res+=i print(res)
实例046:打破循环
求输入数字的平方,如果平方运算后小于 50 则退出。
1 2 3 4 5 6 7 8 9 10 11
whileTrue: try: n = float(input('输入一个数字:')) except: print('错误输入') continue dn = n**2 print (str(n)+'的平方是'+dn) if dn<50: print("平方小于50,退出") break
from tkinter import * canvas=Canvas(width=800,height=600,bg='yellow') canvas.pack(expand=YES,fill=BOTH) k=1 j=1 for i in range(26): canvas.create_oval(310-k,250-k,310+k,250+k,width=1) k+=j j+=0.3 mainloop()
if __name__ == '__main__': from tkinter import * canvas = Canvas(width = 300,height = 300,bg = 'green') canvas.pack(expand = YES,fill = BOTH) x0 = 150 y0 = 100 canvas.create_oval(x0 - 10,y0 - 10,x0 + 10,y0 + 10) canvas.create_oval(x0 - 20,y0 - 20,x0 + 20,y0 + 20) canvas.create_oval(x0 - 50,y0 - 50,x0 + 50,y0 + 50) import math B = 0.809 for i in range(16): a = 2 * math.pi / 16 * i x = math.ceil(x0 + 48 * math.cos(a)) y = math.ceil(y0 + 48 * math.sin(a) * B) canvas.create_line(x0,y0,x,y,fill = 'red') canvas.create_oval(x0 - 60,y0 - 60,x0 + 60,y0 + 60)
for k in range(501): for i in range(17): a = (2 * math.pi / 16) * i + (2 * math.pi / 180) * k x = math.ceil(x0 + 48 * math.cos(a)) y = math.ceil(y0 + 48 + math.sin(a) * B) canvas.create_line(x0,y0,x,y,fill = 'red') for j in range(51): a = (2 * math.pi / 16) * i + (2* math.pi / 180) * k - 1 x = math.ceil(x0 + 48 * math.cos(a)) y = math.ceil(y0 + 48 * math.sin(a) * B) canvas.create_line(x0,y0,x,y,fill = 'red') mainloop()
实例060:字符串长度
计算字符串长度。
1 2
s='renlinjie101' print(len(s))
实例061:杨辉三角
打印出杨辉三角形前十行。
1 2 3 4 5 6 7 8
defgenerate(numRows): r = [[1]] for i in range(1,numRows): r.append(list(map(lambda x,y:x+y, [0]+r[-1],r[-1]+[0]))) return r[:numRows] a=generate(10) for i in a: print(i)
if __name__ == '__main__': from tkinter import * x = 360 y = 160 top = y - 30 bottom = y - 30 canvas = Canvas(width = 400,height = 600,bg = 'white') for i in range(20): canvas.create_oval(250 - top,250 - bottom,250 + top,250 + bottom) top -= 5 bottom += 5 canvas.pack() mainloop()
实例64:画椭圆、矩形
利用ellipse 和 rectangle 画图。。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
if __name__ == '__main__': from tkinter import * canvas = Canvas(width = 400,height = 600,bg = 'white') left = 20 right = 50 top = 50 num = 15 for i in range(num): canvas.create_oval(250 - right,250 - left,250 + right,250 + left) canvas.create_oval(250 - 20,250 - top,250 + 20,250 + top) canvas.create_rectangle(20 - 2 * i,20 - 2 * i,10 * (i + 2),10 * ( i + 2)) right += 5 left += 5 top += 10
AspectRatio = 0.85 MAXPTS = 15 h = screeny w = screenx xcenter = w / 2 ycenter = h / 2 radius = (h - 30) / (AspectRatio * 2) - 20 step = 360 / MAXPTS angle = 0.0 for i in range(MAXPTS): rads = angle * math.pi / 180.0 p = PTS() p.x = xcenter + int(math.cos(rads) * radius) p.y = ycenter - int(math.sin(rads) * radius * AspectRatio) angle += step points.append(p) canvas.create_oval(xcenter - radius,ycenter - radius, xcenter + radius,ycenter + radius) for i in range(MAXPTS): for j in range(i,MAXPTS): canvas.create_line(points[i].x,points[i].y,points[j].x,points[j].y)
canvas.pack() mainloop() if __name__ == '__main__': LineToDemo()
实例066:三数排序
输入3个数a,b,c,按大小顺序输出。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
raw=[] for i in range(3): x=int(input('int%d: '%(i))) raw.append(x) for i in range(len(raw)): for j in range(i,len(raw)): if raw[i]>raw[j]: raw[i],raw[j]=raw[j],raw[i] print(raw)
raw2=[] for i in range(3): x=int(input('int%d: '%(i))) raw2.append(x) print(sorted(raw2))
if __name__ == '__main__': nmax = 50 n = int(input('请输入总人数:')) num = [] for i in range(n): num.append(i + 1) i = 0 k = 0 m = 0 while m < n - 1: if num[i] != 0 : k += 1 if k == 3: num[i] = 0 k = 0 m += 1 i += 1 if i == n : i = 0 i = 0 while num[i] == 0: i += 1 print(num[i])
N = 3 #stu # num : string # name : string # score[4]: list student = [] for i in range(5): student.append(['','',[]]) definput_stu(stu): for i in range(N): stu[i][0] = input('input student num:\n') stu[i][1] = input('input student name:\n') for j in range(3): stu[i][2].append(int(input('score:\n'))) defoutput_stu(stu): for i in range(N): print ('%-6s%-10s' % ( stu[i][0],stu[i][1] )) for j in range(3): print ('%-8d' % stu[i][2][j]) if __name__ == '__main__': input_stu(student) print (student) output_stu(student)
defreverse(self, head): if head isNoneand head.next isNone: return head pre = head cur = head.next while cur isnotNone: temp = cur.next cur.next = pre pre = cur cur = temp head.next = None return pre
defprint_list(self, head): init_data = [] while head isnotNone: init_data.append(head.get_data()) head = head.next return init_data
if __name__=='__main__': head=Node('head') link=List(head) for i in range(10): node=Node(i) link.append(node) print(link.print_list(head))
defreverse(self, head): if head isNoneand head.next isNone: return head pre = head cur = head.next while cur isnotNone: temp = cur.next cur.next = pre pre = cur cur = temp head.next = None return pre
defprint_list(self, head): init_data = [] while head isnotNone: init_data.append(head.get_data()) head = head.next return init_data
if __name__=='__main__': head=Node('head') link=List(head) for i in range(10): node=Node(i) link.append(node) print(link.print_list(head)) print(link.print_list(link.reverse(head)))
实例074:列表排序、连接
列表排序及连接。
程序分析:排序可使用 sort() 方法,连接可以使用 +号或 extend()方法。
1 2 3 4 5
a=[2,6,8] b=[7,0,4] a.extend(b) a.sort() print(a)
实例075:不知所云
1 2 3 4 5 6 7 8
if __name__ == '__main__': for i in range(5): n = 0 if i != 1: n += 1 if i == 3: n += 1 if i == 4: n += 1 if i != 4: n += 1 if n == 3: print (64 + i)
defpeven(n): i = 0 s = 0.0 for i in range(2, n + 1, 2): s += 1.0 / i return s
defpodd(n): s = 0.0 for i in range(1, n + 1, 2): s += 1.0 / i return s
defdcall(n): if n % 2 == 0: s = peven(n) else: s = podd(n) return s
if __name__ == '__main__': n = int(input('input a number: ')) sum = dcall(n) print(sum)
实例077:循环遍历列表
循环输出列表
1 2 3 4
from itertools import cycle l=['moyu','niupi','xuecaibichi','shengfaji','42'] for i in cycle(l): print(i)
实例078:字典
找到年龄最大的人,并输出。请找出程序中有什么问题。
1 2 3 4 5 6 7 8
if __name__ == '__main__': person = {"li":18,"wang":50,"zhang":20,"sun":22} m = 'li' for key in person.keys(): if person[m] < person[key]: m = key print ('%s,%d' % (m,person[m]))
if __name__ == '__main__': m = 0 j = 1 x = 0 while (m < 5) : x = 4 * j for i in range(0,5) : if(x%4 != 0) : m=0 break else : m += 1 x = (x/4) * 5 +1 j += 1 print(x)
if __name__ == '__main__': import time start = time.time() for i in range(3000): print(i) end = time.time() print (end - start)
实例093: time模块Ⅲ
疑惑???
1 2 3 4 5 6 7 8 9
if __name__ == '__main__': import time start = time.clock() print (start) for i in range(3000): print(i) end = time.clock() print (end) print('different is %6.3f' % (end - start))
if __name__ == '__main__': import time import random play_it = input('do you want to play it.(\'y\' or \'n\')') while play_it == 'y': c = input('input a character:\n') i = random.randint(0,2**32) % 100 print ('please input number you guess:\n') start = time.clock() a = time.time() guess = int(input('input your guess:\n')) while guess != i: if guess > i: print('please input a little smaller') guess = int(input('input your guess:\n')) else: print('please input a little bigger') guess = int(input('input your guess:\n')) end = time.clock() b = time.time() var = (end - start) / 18.2 print (var) # print 'It took you %6.3 seconds' % time.difftime(b,a)) if var < 15: print ('you are very clever!') elif var < 25: print ('you are normal!') else: print ('you are stupid!') print ('Congradulations') print ('The number you guess is %d' % i) play_it = input('do you want to play it. y or n?')
from sys import stdout if __name__ == '__main__': filename = input('输入文件名:\n') fp = open(filename, "w") ch = input('输入字符串:\n') while ch != '#': fp.write(ch) stdout.write(ch) ch = input('') fp.close()
实例098:磁盘写入Ⅱ
从键盘输入一个字符串,将小写字母全部转换成大写字母,然后输出到一个磁盘文件”test”中保存。
使用with…as..更简洁
1 2 3 4 5 6 7
if __name__ == '__main__': with open('./test.txt','w') as f: string = input('please input a string:\n') string = string.upper() f.write(string) with open ('./test.txt','r') as f2: print(f2.read())
if __name__ == '__main__': with open('test1.txt','r') as f1: str1=f1.read() with open ('test2.txt','r') as f2: str2=f2.read() with open ('test3.txt','w') as f3: l = list(str1+str2) l.sort() s = '' s = s.join(l) f3.write(s)
实例100:列表转字典
列表转换为字典。
1 2 3 4 5
i = ['A','B'] l = [1,2] # i = ['A','B','A'] # l=[1,2,3] print (dict(zip(i,l)))