Hi I'm trying to write a function to find the factorial product of any given number. For example for factorial (6) I would get the product of 6*5*3*2*1.
so for factorial(3) the output would be 6.
The functions I have so far are:
import functools
def mult(x, y):
return x * y
def factorial(n):
if n == 0:
return 1
else:
functools.reduce(mult(n,factorial(n - 1)))
But I keep getting an error that Python is expecting 2 arguments and 1 is given. I know I have to use range
somehow but I can't figure it out. How do I edit my existing code so that it runs properly?
you can do this pretty easily:
>>> import functools, operator
>>> functools.reduce(operator.mul, xrange(1, 6))
120
Note that the first argument is a function (you're passing the result of a function call). the second argument is an iterable. Also note that written this way, no recursion is needed...
operator.mul
is equivalent to your mult
function
import functools
def factorial(n):
if n == 0:
return 1
else:
return functools.reduce(lambda x,y: x*y, range(1,n+1))
print factorial(3)
Of course you can use you own multi function instead of the lambda if you prefer.
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