Python exercise 013: Solving a + aa + aaa ......, Python
[Python exercise 013]Evaluate the value of s = a + aa + aaa + aaaa + aa... a, where a is a number. For example, 2 + 22 + 222 + 2222 + 22222 (a total of 5 numbers are added at this time.
This question is not difficult. In fact, a + aa + aaa + aa... a can be converted to (a * 10 ** 0) + (a * 10 ** 1) + (a * 10 ** 2 )...... Then convert it to a * (10 ** 0 + 10 ** 1 + 10 ** 2 ......), So we can use two for loops.
Note: for 1st for loops, range () must be counted from 1, so that the first 2nd for loops can be cyclically at least once (if I = 0, then range (I) it cannot be recycled.
The Code is as follows:
A = int (input ('Enter the number a: ') count = int (input ('enter a few numbers and add them together :')) res = 0 # initialize the Final Solution for I in range (1, count + 1): # The number of cycles is the same as the input value, but starting from 1, the loop t = 0 # The temporary variable for j in range (I ): t = t + 10 ** j # Calculate 10 ** 0 + 10 ** 1 +... + 10 ** j res = res + (a * t) # Calculate a * tprint (res)
The output result is as follows:
Enter the number a: 5
Enter a few numbers to add: 4
6170
++
Source: getting started with programming languages: 100 typical examples [Python]