古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?
程序分析:兔子的规律为数列1,1,2,3,5,8,13,21....
def theNumberOfRabbits(self, month):
'每个月有多少对兔子'
month = int(month)
if month == 1:
return [1]
if month == 2:
return [2]
tempList = [1, 1]
for i in range(2, month):
tempList.append(tempList[- 1] + tempList[- 2])
for j in range(0, len(tempList)):
print("%d月份有%d对兔子" % (j+1, tempList[j]))
return tempList
运行结果:
1月份有1对兔子
2月份有1对兔子
3月份有2对兔子
4月份有3对兔子
5月份有5对兔子
6月份有8对兔子
7月份有13对兔子
8月份有21对兔子
9月份有34对兔子
10月份有55对兔子
281

被折叠的 条评论
为什么被折叠?



