Python 练习实例21
题目:猴子吃桃问题:猴子第一天摘下若干个桃子,当即吃了一半,还不瘾,又多吃了一个第二天早上又将剩下的桃子吃掉一半,又多吃了一个。以后每天早上都吃了前一天剩下的一半零一个。到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘了多少。
程序分析:采取逆向思维的方法,从后往前推断。
程序源代码:
实例(Python 2.0+)
以上实例输出结果为:
1534
题目:猴子吃桃问题:猴子第一天摘下若干个桃子,当即吃了一半,还不瘾,又多吃了一个第二天早上又将剩下的桃子吃掉一半,又多吃了一个。以后每天早上都吃了前一天剩下的一半零一个。到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘了多少。
程序分析:采取逆向思维的方法,从后往前推断。
程序源代码:
以上实例输出结果为:
1534
健健
459***[email protected]
Python3 参考方案:
#!/usr/bin/python3 x = 1 for day in range(0,9): x = (x+1)*2 print(x)
公式推导
x÷2-1=1 x÷2=2 x = 4 4=(1+1)×2
健健
459***[email protected]
菜鸟1001号
176***[email protected]
参考方法:
#!/usr/bin/python # -*- coding: UTF-8 -*- m = [1] Tn = 1 for i in range(9): Tn = (Tn+1)*2 m.append(Tn) print(m[len(m)-1])
菜鸟1001号
176***[email protected]
莫哉啼
695***[email protected]
Python3 参考方法:
#!/usr/bin/python3 x1=1 n1=9 while n1>0: x1=(x1+1)*2 print(n1,x1) n1=n1-1
莫哉啼
695***[email protected]
强哥1号拖拉机
249***[email protected]
使用递归:
#!/usr/bin/env python # -*- coding: utf-8 -*- def taozi(n): if n == 1: return 1 else: return (taozi(n-1)+1)*2 print taozi(10) #递归思路
强哥1号拖拉机
249***[email protected]
关山月
15z***[email protected]
Python2.x 与 Python3.x 兼容:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
daypeach = []
daypeach.append(1)
curpeaches = lambda x: (x + 1) * 2
for i in range(0, 9):
daypeach.append(curpeaches(daypeach[i]))
print('第一天共摘了%d个' % daypeach[9])关山月
15z***[email protected]
funzmg
fun***@gmail.com
利用正序的递归排序,使用的是Python 3.6
# -*- coding:UTF-8 -*- def fun(x): if x==10: return 1 else: return (fun(x+1)+1)*2 print(fun(1))
funzmg
fun***@gmail.com
paul
fly***[email protected]
使用递归,在前面大神的基础上简化了语句,并且输出每天有多少桃子,摘了多少:
# -*- coding: UTF-8 -*-
def peach(n):
return 1 if n==1 else (peach(n-1)+1)*2
for i in range(1,11):
print('第%d天原有%d个桃子,摘了%d个'%(i,peach(11-i),peach(11-i)/2+1))paul
fly***[email protected]
kuraki
117***[email protected]
Python3 下测试:
def fun(day):
if day==9:
return 4
else:
return (fun(day+1)+1)*2
for i in range(1,10+1):
if i == 10:
print('第10天猴子见到桃子只有1个')
else:
print(f'第{i}天有桃子{fun(i)}个,吃掉{int((fun(i)/2)+1)}个')kuraki
117***[email protected]