Small computing exercises ---

  • Title: seeking s = a + aa + aaa + aaaa + aa ... the value of a, where a is a number. E.g. 2 + 22 + 222 + 2222 + 22222 (in this case the sum total of the number 5), the number added by several keyboard.
  • Program Analysis: The key is to calculate the value of each item.
  • Code
. 1  from functools Import the reduce
 2 Tn of = 0
 . 3 of Sn = [] # initializes a list 
. 4 n-= int (INPUT ( ' n-= ' ))
 . 5 A = int (INPUT ( ' A = ' ))
 . 6  for COUNT in Range ( n-):
 . 7      Tn of Tn of = + A
 . 8      A * A = 10
 . 9      Sn.append (Tn of)
 10      Print (Tn of)
 . 11  
12 is of Sn = the reduce ( the lambda X, Y: X + Y, of Sn)
 13 is Print ( " Calculation Results: " , of Sn)
  • result

 . 5 = n- A = 77. 7. 7 777 7777 77777 Calculation Results: 86,415

  • About reduce ()

reduce () function parameter sequence elements have accumulated.

All data is a function of data set (a list, tuple, etc.) are the following: (two parameters) of the first set of first and second elements with the function operates in the function passed to reduce,

The results obtained with the function of re-calculation function to the third data, to obtain a final result.

reduce () function Syntax: the reduce ( function , Iterable [, initializer of ])

function - a function, there are two parameters

iterable - iterables

initializer - Optionally, the initial parameter

>>> the reduce ( the Add , [ . 1 , 2 , . 3 , . 4 , . 5 ] ) # calculates list:

1+2+3+4+5

15

>>> the reduce ( lambda X , Y : X + Y , [ . 1 , 2 , . 3 , . 4 , . 5 ] ) # anonymous function using lambda

15

Guess you like

Origin www.cnblogs.com/monsterhy123/p/12562769.html