Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to fix reduce() of empty sequence with no initial value error?

Tags:

python

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
like image 448
Aditya Varma Indukuri Avatar asked Jan 01 '19 16:01

Aditya Varma Indukuri


1 Answers

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.

like image 127
Rory Daulton Avatar answered Oct 14 '22 14:10

Rory Daulton