假設狗一年1歲,第3年和第5年個生出一條小狗,第六年死亡,計算第n年狗的個數(不考慮公母)
阿新 • • 發佈:2018-12-28
2種演算法
先定義一個狗的class
class Dog:
year = 1
def is_dead(self):
return True if self.year >= 6 else False
def add(self):
self.year += 1
def proc(self):
return True if self.year == 3 or self.year == 5 else False
處理狗的增長問題
def prot(a):
num = 0
for i in range(len(a))[::-1]:
a[i].add()
if a[i].proc(): num += 1
if a[i].is_dead(): del a[i]
for i in range(num):
a.append(Dog())
return a
1,普通的for迴圈
def fordemo(n):
a = []
for i in range(n):
if i == 0:
a = [Dog()]
else:
a = prot(a)
return a
# value = fun(6)
value = fordemo(6)
for row in value:
print row.year
2,遞迴,更加簡單了
def fun(n):
if n == 1:
return [Dog()]
else:
return prot(fun(n - 1))
value = fordemo(6)
for row in value:
print row.year
用Python實現的,清晰明朗,哈哈