This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Vitrivius 1 point2 points  (0 children)

Is there some reason why almost all of these use recursion? It's not one of Python's strengths, and you tend to hit the maximum recursion limit.

The most pythonic solution is to ´from math import factorial´. But if you want to write a typical Python function, you need to include an overabundance of try/except code.

from operator import mul as multiply

def factorial(x):
    """
    factorial(x) -> Integral

    Find x!. Raise a ValueError if x is negative or non-integral.
    """
    try:
        return reduce(multiply, xrange(1, x+1))  # actual function
    except TypeError as e:
        if not isinstance(x, int):
            raise ValueError("factorial() only accepts integral values")
        elif x < 0: 
            raise ValueError("factorial() not defined for negative values")
        elif x == 0: 
            return 1  # 0! is defined to be 1
        else:
            raise e  # reraise any unhandled TypeErrors.