2

I am new to Python, and am just learning the syntax and various functions. I would like to know if

x=reduce((lambda x,y: x*y) , [x for x in range(5) if x > 0])

is a correct function for calculating the factorial of a number ?

Kind Regards

1
  • Are you new to programming or new to Python? You should use the factorial function from the mathmodule. Commented Oct 21, 2013 at 9:57

5 Answers 5

6

Something along the lines of http://www.willamette.edu/~fruehr/haskell/evolution.html

# beginner

def fac(n):
    f = 1
    i = 1
    while i <= n:
        f *= i
        i += 1
    return f

# advanced beginner

def fac(n):
    return n * fac(n - 1) if n > 1 else 1

# intermediate

def fac(n):
    return reduce(lambda x, y: x * y, range(1, n + 1))

# advanced intermediate

import operator
def fac(n):
    return reduce(operator.mul, xrange(1, n + 1))

# professional

import math
print math.factorial(5)

# guru

import scipy.misc as sc
print sc.factorial(5, exact=True)
Sign up to request clarification or add additional context in comments.

Comments

4

Short:

x = reduce(lambda x,y: x*y, range(1,5))

Shorter, Instead of a lambda:

from operator import mul
x = reduce(mul, range(1,5))

Or Shortest, from math module (thanks to hop):

from math import factorial
factorial(4) # range/xrange above does not include the upper value

Comments

3

Pretty much -- though if you want 5!, you should do range(6). Also, a small stylistic issue: you should surround your generator expression with parentheses instead of brackets, so that a temporary list doesn't need to be constructed. Finally, the if-clause isn't necessary -- just use the two-argument version of range.

3 Comments

or even just use range(1,6) in place of the entire list/generator comprehension.
Hah, you beat me to it.
And on top of it, you can use operator.mul instead of the lambda (import operator first).
1
def factorial(n):return reduce(lambda x,y:x*y,[1]+range(1,n+1))

2 Comments

Better: reduce(lambda x,y:x*y, xrange(1, n+1), 1)
I use def, to define a function factorial(n), so each line you need to do factorial function, just call factorial(n), so you avoid to write reduce(lambda x,y:x*y, xrange(1, n+1), 1) each line you need it
1

Another approach using recursion:

def factorial(n):
    if n == 0:
        return 1
    else:
        return n*factorial(n-1)

Anyway, it's better to use math.factorial.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.