The reduce () function is also a high-order function built into Python. The reduce () function receives a parameter similar to map (), a function f, a list, but behaves differently from map (), and reduce () the incoming function f must receive two parameters, and reduce () calls function f repeatedly on each element of the list and returns the final result value.
For example, write an F function that receives x and Y, and returns the and of X and Y:
def f (x, y): return x + y
When you call reduce (f, [1, 3, 5, 7, 9]), the Reduce function calculates the following:
First two elements are calculated: F (1, 3), the result is 4, and the result and the 3rd element are calculated: F (4, 5), the result is 9, and the result and the 4th element are calculated: F (9, 7), the result is 16, and the result and the 5th element are calculated: F ( 9), the result is 25; because there are no more elements, the calculation ends and the result 25 is returned.
The above calculation is actually a summation of all the elements of the list. Although Python has built-in sum function sum (), it is simple to sum with reduce ().
Reduce () can also receive a 3rd optional parameter as the initial value of the calculation. If you set the initial value to 100, the calculation:
Reduce (f, [1, 3, 5, 7, 9], 100)
The result will change to 125 because the first round calculation is:
Calculates the initial value and the first element: F (100, 1), and the result is 101.
Practice:
Python has built-in sum function sum (), but there is no quadrature function, use reduce () to calculate the product:
Input: [2, 4, 5, 7, 12]
Output: Results of 2*4*5*7*12
Method:
def prod (x, y): return x*yprint reduce (prod, [2, 4, 5, 7, 12])
Results:
>>>3360
The reduce () function in Python