Python 練習實例24
題目:有一分數序列:2/1,3/2,5/3,8/5,13/8,21/13...求出這個數列的前20項之和。
程序分析:請抓住分子與分母的變化規(guī)律。
程序源代碼:
方法一:
#!/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
方法三:
#!/usr/bin/python # -*- coding: UTF-8 -*- a = 2.0 b = 1.0 l = [] for n in range(1,21): b,a = a,a + b l.append(a / b) print reduce(lambda x,y: x + y,l)
以上實例輸出結果為:
32.6602607986
更多建議: