练笔。
猴子吃桃,每天吃一半,又多吃一个;最后剩一个,问5天前总共有多少个桃子。很简单,不废话,直接上代码。
1 #!/usr/bin/env python3
2 #coding=utf-8
3 # version 3.0.7
4 #循环算法
5 n = 1
6 for date in range(5,0,-1):
7 n=(n+1) <<1
8 print(n)
9
10 #递归算法
11 def monkey(peace,count,day):
12 if count == 0 :
13 print('%2d days before ,there is %2d peaces' %(day,peace))
14 else :
15 peace=peace*2+2
16 count-=1
17 monkey(peace,count,day)
18 if __name__ == '__main__' :
19 day=int(input('please input the total days:'))
20 peace=int(input('please input the rest:'))
21 monkey(peace,day,day)
$ ./猴子吃桃问题.py
94
please input the total days:5
please input the rest:1
5 days before ,there is 94 peaces