Python Practice Example 24
Problem:There is a fractional sequence: 2/1, 3/2, 5/3, 8/5, 13/8, 21/13... Find the sum of the first 20 terms of this sequence.
Program analysis:Please grasp the changing pattern of the numerator and denominator.
Program source code:
Method 1:
Example
#!/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)
Method 2:
Example
#!/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)
Method 3:
Example (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)
Example (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))
The output of the above example is:
32.6602607986Other extensions
Python 100 Examples