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

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
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值