16、题目:猴子吃桃问题:猴子第一天摘下若干个桃子,当即吃了一半,还不瘾,又多吃了一个第二天早上又将剩下的桃子吃掉一半,又多吃了一个。以后每天早上都吃了前一天剩下的一半零一个。到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘了多少。
程序分析:采取逆向思维的方法,从后往前推断。
xn=1
for x in xrange(1,10):
xn=2*(xn+1)
print xn
17、题目:两个乒乓球队进行比赛,各出三人。甲队为a,b,c三人,乙队为x,y,z三人。已抽签决定比赛名单。有人向队员打听比赛的名单。a说他不和x比,c说他不和x,z比,请编程序找出三队赛手的名单。
import itertools
team1=('a','b','c')
team2_all_order=list(itertools.permutations('xyz',3)) #list all the order of xyz
for x in xrange(len(team2_all_order)):
matched=zip(team1,team2_all_order[x]) #zip the team1 and team2_all the order
if matched[0][1]!='x':# matched[0] is a truple of ('a','*')
if matched[2][1]!='x' and matched[2][1]!='z':# matched[2] is truple of ('c','*')
print matched
18、题目:打印出如下图案(菱形):
for x in xrange(1,8):
if x<=4:
print (7-(2*x-1))/2*' '+(2*x-1)*'*'+(7-(2*x-1))/2*' '
else:
j=8-x
print (7-(2*j-1))/2*' '+(2*j-1)*'*'+(7-(2*j-1))/2*' '
19、题目:有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和。
程序分析:请抓住分子与分母的变化规律。
x,y,result=1.0,1.0,0.0
for i in xrange(0,20):
temp=x
x=x+y
y=temp
result+=x/y
print result
扫描二维码关注公众号,回复:
2787017 查看本文章
20、题目:求1+2!+3!+...+20!的和。
程序分析:此程序只是把累加变成了累乘。
k,result=1,0
for i in xrange(1,21):
k*=i
result+=k
print result