How on Factorial

Chris Rebert clp2 at rebertia.com
Wed Oct 27 03:03:10 EDT 2010


On Tue, Oct 26, 2010 at 11:25 PM, Geobird <a1chandan at gmail.com> wrote:
>
>  I  am a beginner in Python and would ask for a help.
>
>
> I  was searching for  smaller  version  of  code  to calculate
> factorial . Found  this one
> def fact(x):
>        return x > 1 and x * fact(x - 1) or 1
>
>  But I don't  really get how (  ....x > 1 and x * fact(x - 1)....)
> works .

It exploits short-circuit evaluation
(http://en.wikipedia.org/wiki/Short-circuit_evaluation ). This is
stunt coding / code golf; no one should actually write factorial like
that.

For pedagogical purposes, the code is equivalent to:
def fact(x):
    # begin AND
    result = x > 1
    if result: # x was > 1
        result = x * fact(x - 1) # Recursive Case
    # end AND
    # begin OR
    if not result:
        result = 1 # Base Case; x was <= 1, so result was False and we
didn't recurse.
        # If we did recurse, then result = x!, and
        # since x! is always nonzero,
        # and Python considers nonzero numbers to be boolean true,
        # then we won't even enter this `if`.
    # end OR
    return result

Note that `and` has higher precedence than `or` in Python.

Also, as of Python 2.6.6 (and possibly earlier), there's a built-in
factorial function in the `math` std lib module, so there's no need to
write one:
Python 2.6.6 (r266:84292, Oct 12 2010, 14:31:05)
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from math import factorial
>>> factorial(5)
120

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list