When I am trying to find factorial using below code, it is working for all numbers except '0'. When I give the input as 0, below error is displayed. Can some one help me to understand and fix the error
from functools import reduce
n = int(input())
fact = lambda a, b: a*b if (n>=1) else 1
reduce(fact, range(1,n+1))
Expected result: When input is given as '0' 1 should be displayed as output
Actual result: Below error is displayed
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-124-52f472210976> in <module>
3
4 fact = lambda a, b: a*b if (n>=1) else 1
----> 5 reduce(fact, range(1,n+1))
6
TypeError: reduce() of empty sequence with no initial value
In Python 3, at least, reduce()
has an "initializer" parameter, which "is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty" (documentation). So use an initializer of 1
. You can also simplify your code by using the multiplication operator in the operator
module.
from functools import reduce
from operator import mul
result = reduce(mul, range(1,n+1), 1)
You should understand your error now. The error message says that you tried to use reduce()
on an empty sequence with no initial value
. Putting in the initial value of 1
solves that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With