Python Practice Example 18
Problem:Find the value of s=a+aa+aaa+aaaa+aa...a, where a is a digit. For example, 2+22+222+2222+22222 (in this case, 5 numbers are added together), and how many numbers to add is controlled by the keyboard.
Program analysis:The key is to calculate the value of each term.
Program source code:
Example (Python 2.0+)
#!/usr/bin/python
# -*- coding: UTF-8 -*-
Tn = 0
Sn = []
n = int(raw_input('n = '))
a = int(raw_input('a = '))
for count in range(n):
Tn = Tn + a
a = a * 10
Sn.append(Tn)
print Tn
Sn = reduce(lambda x,y : x + y,Sn)
print "The calculated sum is:",Sn
Example (Python 3.0+)
#!/usr/bin/python
from functools import reduce
Tn = 0
Sn = []
n = int(input('n = '))
a = int(input('a = '))
for count in range(n):
Tn = Tn + a
a = a * 10
Sn.append(Tn)
print (Tn)
Sn = reduce(lambda x,y : x + y,Sn)
print ("The calculated sum is:",Sn)
The output of the above example is:
n = 4 a = 4 4 44 444 4444 计算和为: 4936Other extensions
Python 100 Examples