python中实现兔子问题递推

小鲨鱼2018 / 2023-08-29 / 原文

 

兔子一代生3对,然后每隔一代兔子才有繁殖能力,问最初有1对兔子,问5代后一共有多少只兔子?

001、直接实现

>>> list1 = [1] * 5
>>> list1
[1, 1, 1, 1, 1]
>>> for i in range(2,5):
...     list1[i] = list1[i - 1] + list1[i - 2] * 3
...
>>> list1                ## 1到5代的兔子数目如下
[1, 1, 4, 7, 19]

 

002、借助函数结构实现

[root@pc1 test01]# ls
test.py
[root@pc1 test01]# cat test.py             ## 统计函数
#!/usr/bin/env pythoh
# -*- coding: utf-8 -*-

generation = 5
size = 3

def count(generation, size):
        list1 = [1] * generation
        for i in range(2,generation):
                list1[i] = list1[i - 1] + list1[i - 2] * size
        return list1[generation - 1]

print(count(generation, size))
[root@pc1 test01]# python3 test.py          ## 统计结果
19

 。