Advanced a python (functional programming) [2-3] reduce function in python

2-3 python in the reduce function

python, reduce () function

reduce () function is also built-in Python a higher-order function. reduce () function and parameters received map () is similar to a function f, a list, but the behavior and map () different, reduce () function f must receive the incoming two parameters , the reduce (for each of the list) element repeatedly calling the function f, and returns the final result value .

For example, the preparation of a function f, receiving x and y, x and y and return:

1 def f(x, y):
2     return x + y

Call reduce (f, [1, 3, 5, 7, 9]) when, reduce the function is calculated as follows:

First calculate the first two elements: f (. 1,. 3 ), the result is 4; 
then the results of the third element and is calculated: f ( 4,. 5 ), the result is 9; 
then the results of calculation and the fourth element: f ( 9, 7 ), the result is 16; 
then the results of calculation and the five elements: F ( 16, 9 ), was 25; 
since there are no more elements, the end of the calculation, the result 25 returned.

Calculated above is actually summing all elements of the list. Although Python built-sum function sum (), however, the use of reduce () sum is also very simple.

reduce () may also receive a third optional parameter , as the initial value calculation . If the initial value of 100, calculated:

1 reduce(f, [1, 3, 5, 7, 9], 100)

Results becomes 125, since the first round of calculation is:

And calculating the initial value of the first element: f (100, 1), the result is 101.

task

Python built-sum function sum (), but does not function quadrature, please use recude () to Quadrature:

Input: [2, 4, 5, 7, 12]
Output: Results 2 * 4 * 5 * 7 * 12

1 def prod(x, y):
2     return x * y
3 
4 print reduce(prod, [2, 4, 5, 7, 12])

 

Guess you like

Origin www.cnblogs.com/ucasljq/p/11610862.html