When I searched for a factorial using Python today, the simplest found was to use the reduce built-in function, but when I was using reduce, I reported nameerror: name 'reduce' is not defined. so I searched again and found that after Python 3.0.0.0, reduce is no longer in the built-in function. To use it, I have to import reduce from functools.
For details, seeThe fate of reduce () in Python 3000.
Reduce usage
Reduce (function, sequence [, initial])-> Value
Apply a function of two arguments cumulatively to the items of a sequence,
From left to right, so as to reduce the sequence to a single value.
For example, reduce (lambda X, Y: X + Y, [1, 2, 3, 4, 5]) calculates
(1 + 2) + 3) + 4) + 5). If initial is present, it is placed before the items
Of the sequence in the calculation, and serves as a default when
Sequence is empty.
This means that the function is used continuously for sequence. If initial is not given, two elements of sequence will be transferred for the first call, and the result of the previous call and the next element of sequence will be passed to the function. if initial is given, the first element of initial and sequence is passed to the function for the first time.
>>> From functools import reduce <br/> reduce (lambda X, Y: X + Y, [1, 2, 3]) <br/> 6 <br/> reduce (lambda X, Y: X + Y, [1, 2], 9) <br/> 15 <br/> reduce (lambda X, Y: X + Y, [1, 2, 3], 7) <br/> 13 <br/>