免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1994 | 回复: 0
打印 上一主题 下一主题

python小代码(三) [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2006-04-11 17:57 |只看该作者 |倒序浏览
1.
#一球从100米高度自由落下,每次落地后反跳回原高度的一半;
#再落下,求它在第10次落地时,共经过多少米?第10次反弹多高?
s=100
x=1
i=100
while x!=10:
    i=i*0.5
    s=s+i*2
    x+=1
print "the total of distance is %3.3f\n"%(s)
print "the tenth distance is %1.3f"%(i*0.5)
   
2.
#有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...
#求出这个数列的前20项之和
s,a,b=0.0,2.0,1.0    #赋值为带小数部分是为了识别float型
for i in range(20):
    s=s+a/b
    print a,'/',b
    temp=b
    b=a
    a=a+temp
print "Sum is %9.6f"%(s)

3.
#求1+2!+3!+...+20!的和
s,m,temp=0,0,1
for i in range(1,21):
    m=i*temp
    temp=m
    s=s+m
print s
解析:要注意在运行时temp保存上一次循环的结果。

4.
#利用递归方法求5!
def func(n):
    if n==0|n==1:
        res=1
    elif n>1:
        res=func(n-1)*n
    return res
print func(5)

5.
#给一个不多于5位的正整数,要求:一、求它是几位数,二、逆序打印出各位数字。
#(这里是一种简单的算法,师专数002班赵鑫提供)
x=input("enter: ")
if x==0:
    print "must be positive number"
elif x>99999:
    print "can't enter a number that greater than 99999"
else:
    a=x/10000
    b=x%10000/1000
    c=x%1000/100
    d=x%100/10
    e=x%10
    if a!=0:
        print "it's 5\n%d%d%d%d%d"%(e,d,c,b,a)
    elif b!=0:
        print "it's 4\n%d%d%d%d"%(e,d,c,b)
    elif c!=0:
        print "it's 3\n%d%d%d"%(e,d,c)
    elif d!=0:
        print "it's 2\n%d%d"%(e,d)
    elif e!=0:
        print "it's only 1\n%d"%(e)


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/14719/showart_98378.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP