Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Reduce Function in Python To Find Factorial

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?

like image 405
Whooperton Goldberg Avatar asked Dec 05 '22 05:12

Whooperton Goldberg


2 Answers

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

like image 138
mgilson Avatar answered Dec 08 '22 06:12

mgilson


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.

like image 38
Surya Bista Avatar answered Dec 08 '22 06:12

Surya Bista