【Python】三個例子教你寫代碼
阿新 • • 發佈:2017-11-24
位數 mage int 1-1000 image end src orm origin
這篇文章包括用Python編寫的斐波那契數列,三位數的水仙花數和百錢買百雞的基礎代碼:
(一)斐波那契數列:
‘‘‘
def hanshu(n):
n_1 = 1
n_2 = 1
m = n
sumn = 0
for a in range(1,m+1):
if m == 1:
return n_1
if m== 2:
return n_2
sumn = n_1 + n_2
n_2 = n_1
n_1 = sumn
print(sumn,end = " ")
hanshu(20)
‘‘‘
下圖為以上代碼運行結果:
(二)找出1-1000之內的水仙花數:
def hanshu(n):
sumn = 0
m = n
for dix in range(1,4):
m = m % 10
sumn = sumn + m ** 3
m = n // 10
if sumn == n:
print(n,end = " ")
def hanshu1():
for b in range(1,1000):
hanshu(b)
hanshu1()
下圖為以上代碼運行結果:
(三)百錢買百雞:公雞5元一只,母雞3元一只,小雞0.5元一只,100塊錢買100只雞
問:應該買多少只公雞母雞和小雞,一共有幾種買法?
設:公雞為x只,母雞為y只,小雞為z只
x = 0
while x <= 100:
y = 0
while y <= 100:
z = 0
while z <= 100:
if x + y + z == 100 and 5 * x +3 * y +0.5 * z == 100:
print(x,y,z)
z += 1
y += 1
x += 1
下圖為以上代碼運行結果:
本文為原創文章,轉載請註明出處。
【Python】三個例子教你寫代碼