天天看點

Python 100例實戰訓練——day01Python 練習執行個體1Python 練習執行個體2

參考資料:Python 100例

Python 練習執行個體1

Python 100例題目:有四個數字:1、2、3、4,能組成多少個互不相同且無重複數字的三位數?各是多少?
 程式分析:可填在百位、十位、個位的數字都是1、2、3、4。組成所有的排列後再去掉不滿足條件的排列。           

複制

解法一:

# 基礎解法,循環嵌套
l = []
for i in range(1,5):
    for j in range(1,5):
        for k in range(1,5):
            if( i != k ) and (i != j) and (j != k):
                a = 100*i+10*j+k
                l.append(a)
print(f"共有{len(l)}個",l)           

複制

解法二:

# 調用第三方庫,排列組合
# # 組合
# from scipy.special import comb
# # 階乘
# from scipy.special import factoral
# 排列
from scipy.special import perm
print( perm(4,3))
# 從序列中取2個元素進行組合、元素不允許重複
import itertools as it
for e in it.permutations('1234', 3):
    print(''.join(e), end=', ')           

複制

itertools的使用可參考:Python的排列組合函數

Python 練習執行個體2

Python 100例題目:企業發放的獎金根據利潤提成。
 利潤(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,求應發放獎金總數?
 程式分析:請利用數軸來分界,定位。注意定義時需把獎金定義成長整型。           

複制

解法一:

# 基礎版 if判斷
i = int(input('淨利潤(萬元):'))
if i <=10:
    account = i*10/100
elif i <=20:
    account = (i-10)*7.5/100+10*10/100
elif i <=40:
    account = (i-20)*5/100+10*7.5/100+10*10/100
elif i<=60:
    account = (i-40)*3/100+20*5/100+10*7.5/100+10*10/100
elif i <=100:
    account = (i-60)*1.5/100+20*3/100+20*5/100+20*7.5/100+10*10/100
else:
    account = (i-100)*1/100+40*1.5/100+20*3/100+20*5/100+10*7.5/100+10*10/100
print(f"利潤提成{account}")           

複制

解法二:

# 數軸定位
i = int(input('淨利潤(萬元):'))
arr = [100,60,40,20,10,0]
rat = [0.01,0.015,0.03,0.05,0.075,0.1]
r = 0
for idx in range(0,6):
    if i>arr[idx]:
        r+=(i-arr[idx])*rat[idx]
        print ((i-arr[idx])*rat[idx])
        i=arr[idx]
print (r)           

複制

解法三:

# cut 區間切分===》邏輯有點兒複雜,主要是想給大家介紹下pandas的cut函數,資料切分,解決這個問題比較複雜,用在其他問題上還是比較友善的
import pandas as pd
# 數軸定位
I= int(input('淨利潤(萬元):'))
bins = [0, 11, 21, 41, 61, 101,1000000000000]  #1000000000000 bins要比labels多一個,選一個特别大的數
rats = [0.1, 0.075, 0.05, 0.03, 0.015, 0.01]
par = [10,10,20,20,40,"nan"]
df = pd.DataFrame(list(zip(bins,rats,par)),columns=["區間下限","點數","參數"])

labels = df.index.to_list()

idx = pd.cut([I],bins,labels=labels,right= True)[0]

account = 0
for i in range(idx):
    rate0 = df.iloc[i,1]
    parm0 = df.iloc[i,2]
    account += rate0*parm0
#     print(account)
account = account + (I-df.iloc[idx,0]+1)*df.iloc[idx,1]
print(account)           

複制