1.题目:app
企业发放的奖金根据利润提成。利润(I)低于或等于10万元时,奖金可提10%;函数
利润高于10万元,低于20万元时,低于10万元的部分按10%提成,高于10万元的部分,可提成7.5%;优化
20万到40万之间时,高于20万元的部分,可提成5%;40万到60万之间时高于40万元的部分,可提成3%;spa
60万到100万之间时,高于60万元的部分,可提成1.5%,高于100万元时,超过100万元的部分按1%提成code
从键盘输入当月利润I,求应发放奖金总数?对象
本身的答案:blog
1 profit = int(input("Your profit:")) 2 if profit <= 100000: 3 bonus = profit*0.1
4 elif profit <= 200000: 5 bonus = 100000*0.1+(profit-100000)*0.075
6 elif profit <= 400000: 7 bonus = 100000*0.1+100000*0.075+(profit-200000)*0.05
8 elif profit <= 600000: 9 bonus = 100000*0.1+100000*0.075+200000*0.05+(profit-400000)*0.03
10 elif profit <= 1000000: 11 bonus = 100000*0.1+100000*0.075+200000*0.05+200000*0.03+(profit-600000)*0.015
12 elif profit >= 1000000: 13 bonus = 100000*0.1+100000*0.075+200000*0.05+200000*0.03+400000*0.015+(1000000-profit)*0.01
14 print("Your bonus:",bonus)
优化答案:索引
1 i = int(input('净利润:')) 2 arr = [1000000,600000,400000,200000,100000,0] 3 rat = [0.01,0.015,0.03,0.05,0.075,0.1] 4 r = 0 5 for idx in range(0,6): 6 if i>arr[idx]: 7 r+=(i-arr[idx])*rat[idx] 8 print (i-arr[idx])*rat[idx] 9 i=arr[idx] 10 print r
反思:在遇到元素计算屡次出现时,不要多用if else,能够用列表和for循环遍历的方式来解决。内存
2.题目:input
输入三个整数x,y,z,请把这三个数由小到大输出。
本身的答案:
1 count1 = int(input("输入第一个数:")) 2 count2 = int(input("输入第二个数:")) 3 count3 = int(input("输入第三个数:")) 4 list = [count1,count2,count3] 5 list.sort() 6 print(list)
优化答案:
1 l = [] 2 for i in range(3): 3 x = int(input('integer:\n')) 4 l.append(x) 5 l.sort() 6 print l
反思:遇到让用户输入多个项目的时候能够用列表和for循环遍历。
3.题目:
写函数,检查获取传入列表或元组对象的全部奇数位索引对应的元素,并将其做为新列表返回给调用者。
本身的答案:
1 def my_indexes(content): 2 '''输出参数奇数位索引的值'''
3 new_list = [] 4 for i in range(0,len(content)): 5 if i%2 == 1: 6 new_list.append(content[i]) 7 return new_list 8 val = my_indexes([0,1,2,3,4,5,6,7]) 9 print(val)
优化答案:
1 def my_indexes(content): 2 content = content[1::2] 3 return content 4 val = my_indexes([0,1,2,3,4]) 5 print(val)
反思:切片切片切片,灵活运用!
4.题目:
写函数,检查传入字典的每个value的长度,若是大于2,那么仅保留前两个长度的内容,并将修改后的字典返回
本身的答案:
1 def case_dict(dict): 2 new_dict = {} 3 for k,v in dict.items(): 4 if len(v) > 2: 5 v = v[:2] 6 new_dict[k] = v 7 else: 8 new_dict[k] = v 9 return new_dict 10 print(case_dict({'a':'123456','b':'456','c':'78'}))
优化答案:
1 def case_dict(dict): 2 for key in dict: 3 value = dict[key] 4 if len(value) > 2: 5 dict[key] = value[:2] 6 return dict 7 print(case_dict({'a':'123456','b':'456789','c':'12'}))
反思:尽可能不要建立新字典(当字典特别大的时候,内存负荷太高),for循环不要用 k v 去接收 键 和 值,能够便历 键 ,而后经过键去取值