当前位置: 首页 > 工具软件 > Rabbits > 使用案例 >

The Fun Of Algorithm - Day2 - Rabbits give birth to rabbits

周麒
2023-12-01

Code

'''Scene:
    There is a pair of rabbits. From the third month after birth, they will give birth to one pair of rabbit every month.
    When the little rabbits grows to the third month, they will give birth to another pair of rabbits every month.
    Assuming that all rabbits are immortal, what is the total number of rabbits in each month within 30 months.
'''

# After draw the chart, find out the rabbits number per month follows the Fibonacci sequence rules.

import time
# add timer to calculate the performance
# Basic performance
###############################################################
start = time.time()
fib1 = 1
fib2 = 1
#output the number of the first month and the second month
print('{}    {}'.format(fib1,fib2),end='    ')
i = 3 # set the loop
for i in range(3,31):
    fib = fib1+fib2
    print(fib,end = '    ') #output the amount of each month
    if i%12==0:
        print()  # warp the result around after 12 month
    fib1=fib2
    fib2=fib
    i += 1
end = time.time()
print("The Basic Runtime is {0}".format((end-start)))


# Better performance
###############################################################
start = time.time()
fib1 = 1
fib2 = 1
i = 1

for i in range(16):
    print('{}    {}'.format(fib1,fib2),end='     ')
    if i % 6 == 0:
        print()
    fib1 = fib1+fib2
    fib2 = fib1+fib2
    i=+1
end = time.time()
print("The Better Runtime is {0}".format((end-start)))

Output

1    1    2    3    5    8    13    21    34    55    89    144    
233    377    610    987    1597    2584    4181    6765    10946    17711    28657    46368    
75025    121393    196418    317811    514229    832040    The Basic Runtime is 0.001001119613647461
1    1     
2    3     5    8     13    21     34    55     89    144     233    377     
610    987     1597    2584     4181    6765     10946    17711     28657    46368     75025    121393     
196418    317811     514229    832040     1346269    2178309     The Better Runtime is 0.0
 类似资料:

相关阅读

相关文章

相关问答