實例001:數字組合
題目 有四個數字:1、2、3、4,能組成多少個互不相同且無重複數字的三位數?各是多少?
程序分析 遍歷全部可能,把有重複的剃掉。參考代碼如下:
1.傳統方法
total=0
for i in range(1,5):
for j in range(1,5):
for k in range(1,5):
if ((i!=j)and(j!=k)and(k!=i)):
print(i,j,k)
total+=1
print("共能組成"+str(total)+"個互不相同且無重複數字的三位數")
運行結果如下:
2.簡便方法,根據itertools.permutations()返回可迭代對象的所有數學全排列方式, 用itertools中的permutations即可。
import itertools
sum2=0
a=[1,2,3,4]
for i in itertools.permutations(a,3):
print(i)
sum2+=1
print("共能組成"+str(sum2)+"個互不相同且無重複數字的三位數")
運行結果:
實例002:“個稅計算”
題目 企業發放的獎金根據利潤提成。利潤(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,求應發放獎金總數?
程序分析 分區間計算即可。
while 1:
profit=int(input('請輸入輸入當月利潤: '))
bonus=0
thresholds=[100000,100000,200000,200000,400000]
rates=[0.1,0.075,0.05,0.03,0.015,0.01]
for i in range(len(thresholds)):
if profit<=thresholds[i]:
bonus+=profit*rates[i]
profit=0
break
else:
bonus+=thresholds[i]*rates[i]
profit-=thresholds[i]
bonus+=profit*rates[-1]
print(bonus)
運行結果如下:
實例003:完全平方數
題目 一個整數,它加上100後是一個完全平方數,再加上168又是一個完全平方數,請問該數是多少?
程序分析 因爲168對於指數爆炸來說實在太小了,所以可以直接省略數學分析,用最樸素的方法來獲取上限,最壞的結果是n的平方與(n+1)的平方剛好差168,由於是平方的關係,不可能存在比這更大的間隙。
結合起來:
n=0
while (n+1)**2-n*n<=168:
n+=1
#print(n) 此時打印n爲84
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)
測試結果如下:
實例004:這天第幾天
題目 輸入某年某月某日,判斷這一天是這一年的第幾天?
程序分析 特殊情況,閏年時需考慮二月多加一天:
def isLeapYear(y):
return (y%400==0 or (y%4==0 and y%100!=0))
DofM=[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):
DofM[2]+=1
for i in range(month):
res+=DofM[i]
days = res+day
print("本年第"+str(days)+"天")
測試結果:
實例005:三數排序
題目 輸入三個整數x,y,z,請把這三個數由小到大輸出。
程序分析 練練手就隨便找個排序算法實現一下,偷懶就直接調函數。
1.常規做法
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)
測試結果:
2.簡便方法,用sorted()函數
raw2 = []
for i in range(3):
x = int(input('int%d: ' % (i)))
raw2.append(x)
print(sorted(raw2))
測試結果:
實例006:斐波那契數列
題目 斐波那契數列。斐波那契數列指的是這樣一個數列 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368…這個數列從第3項開始,每一項都等於前兩項之和。
程序分析 斐波那契數列(Fibonacci sequence),從1,1開始,後面每一項等於前面兩項之和。追求方便就遞歸實現,追求性能就用循環。
1.遞歸實現
#遞歸實現
def Fib(n):
return 1 if n<=2 else Fib(n-1)+Fib(n-2)
print(Fib(int(input(""))))
2.樸素實現
#樸素實現
target=int(input())
res=0
a,b=1,1
for i in range(target-1):
a,b=b,a+b
print(a)
測試結果:
結語
當初學完基礎之後,爲了鞏固所學,特意在開源社區github上找了些題刷,大有裨益,很多時候你可能會感覺,自己的思路寫的代碼雖然能解決問題,但是看過人家的代碼後不禁產生一種欽佩甚至仰慕之情。那是菜鳥對老鳥的敬佩與嚮往!
成爲有經驗的老鳥是菜鳥的追求,菜鳥不想菜,那便堅持飛翔!