Python 练习实例24
题目:有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和。
程序分析:请抓住分子与分母的变化规律。
程序源代码:
方法一:
实例
#!/usr/bin/python # -*- coding: UTF-8 -*- a = 2.0 b = 1.0 s = 0 for n in range(1,21): s += a / b t = a a = a + b b = t print (s)
方法二:
实例
#!/usr/bin/python # -*- coding: UTF-8 -*- a = 2.0 b = 1.0 s = 0.0 for n in range(1,21): s += a / b b,a = a , a + b print (s) s = 0.0 for n in range(1,21): s += a / b b,a = a , a + b print (s)
方法三:
实例(Python 2.x)
#!/usr/bin/python # -*- coding: UTF-8 -*- a = 2.0 b = 1.0 l = [] l.append(a / b) for n in range(1,20): b,a = a,a + b l.append(a / b) print reduce(lambda x,y: x + y,l)
实例(Python 3.x)
#!/usr/bin/python from functools import reduce a = 2.0 b = 1.0 l = [] l.append(a / b) for n in range(1,20): b,a = a,a + b l.append(a / b) print (reduce(lambda x,y: x + y,l))
以上实例输出结果为:
32.6602607986
Python 100例
liwei
liw***902@126.com
Python3 环境还可以使用以下方式实现:
#!/usr/bin/python3 a = 2 b = 1 lst = [] for i in range(20): lst.append(str(a) + '/' + str(b)) a,b = a+b, a print('{0} = {1}'.format(eval('+'.join(lst)), '+'.join(lst)))liwei
liw***902@126.com
等一个人
252***465@qq.com
Python3 测试实例:
等一个人
252***465@qq.com
不知道叫啥
114***5830@qq.com
参考方法:
不知道叫啥
114***5830@qq.com
丸子酱
105***8574@qq.com
Python3 参考方法:
#!/usr/bin/python3 n=int(input("Enter a number:")) a=2 b=1 list=[] list1=[] for i in range(1,n+1): list.append(str(a)+'/'+str(b)) list1.append(a/b) c=a a=a+b b=c print(list) print(sum(list1))丸子酱
105***8574@qq.com
奔波儿灞
132***2024@qq.com
基于 python2.7 版本:
#!/usr/bin/python # -*- coding: UTF-8 -*- #有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和。 def function(n,k): a=1 b=2 while(n-1): n=n-1 t=b b = a+b a=t if(k==0): return(a) else: return(b) sum=0.0 float(sum) f=int(raw_input("请输入要查询的项数:")) for i in range(1,f+1): sum = sum +float(function(i,1))/float(function(i,0)) print(sum)奔波儿灞
132***2024@qq.com