Rabbit Birth in python Algorithm Practice (Fibonacci Sequence)
- 2021-12-11 18:08:31
- OfStack
1. Description of the problem
There is a pair of rabbits, and one pair of rabbits is born every month from the third month after birth. The rabbit grows to the third month and then gives birth to a pair of rabbits every month. Assuming that all rabbits are immortal, what is the total logarithm of rabbits every month within 30 months?
2. Problem analysis
The rabbit birth problem is an interesting classical mathematical problem. Let's draw a table to find the law of rabbit number, as shown in the following table
月数 | 小兔子对数 | 中兔子对数 | 老兔子对数 | 兔子总对数 |
---|---|---|---|---|
1 | 1 | 0 | 0 | 1 |
2 | 0 | 1 | 0 | 1 |
3 | 1 | 0 | 1 | 2 |
4 | 1 | 1 | 1 | 3 |
5 | 2 | 1 | 2 | 5 |
6 | 3 | 2 | 3 | 8 |
7 | 5 | 3 | 5 | 13 |
Description: Rabbits less than 1 month are small rabbits, those less than 2 months are middle rabbits, and those over 3 months are old rabbits.
It can be seen that the total number of rabbits per month is 1, 1, 2, 3, 5, 8, 13... This is
Fibonacci
Sequence of numbers. Summing up the sequence law, that is, the rabbit logarithm of the third month can be deduced from the rabbit logarithm of the first two months
3. Algorithm design
This topic is a typical iterative loop, that is, a process in which the old value of a variable is replaced by a new value, and then the new value of a variable is deduced from the old value of the variable. This generation selection is related to these factors:
初值
,
迭代公式
And
选代次数
.
After problem analysis, the algorithm can be described as:
fibn-1 = fiibn-1 = 1(n < 3) Initial value
fibn = fibn-1 + fibn-2 (n ≥ 3) iterative formula
Use
Python
Language to describe the iterative formula is
fib=fibl+fib2
Where fib is the newly calculated free logarithm, fibl is the rabbit logarithm of the previous month,
fib2
fib ② to fib1 ① to fib2 for the first two months, and then to prepare for the next generation, assign the following values
fib2=fib1
,
fibl=fib
Pay attention to the order of assignment; The number of generation selections is controlled by a cyclic variable and is the number of months sought.
4. Complete procedures
Bash
if __name__=="__main__":
fib1 = 1
fib2 = 1
i = 1
while i <= 15: # Find two at a time, so the loop variable loops to 15
print("%8d %8d" %(fib1, fib2), end=" ")
if i % 2 == 0:
print()
fib1 = fib1 + fib2 # Latest 1 Number of rabbits in months
fib2 = fib1 + fib2 # No. 1 4 Number of rabbits in months
i += 1