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 去接收 鍵 和 值,能夠便歷 鍵 ,而後經過鍵去取值