Factorials

Anand Pillai pythonguy at Hotpop.com
Tue Jun 10 14:13:46 CEST 2003


Here is a version that will make the "functional programmers" 
happy. It is iterative rather than recursive.

def fac1(x):
    nums=range(x+1)
    return reduce(lambda x, y: x*y, nums[1:]) 

Here is it's equivalent 'one-liner':

def fac1(x): return reduce(lambda x, y: x*y, (range(x+1))[1:])

Here is another version that uses 'filter' and 'reduce', but
more cryptic:

def fac2(x): return reduce(lambda x, y: x*y, filter(lambda x: x>0, range(x+1)))

The lambda forms are preferred by some programmers since they often
appear more "elegant". 

There might be other ways of doing it using functional programming
approaches. It is an interesting study :-)

Anand Pillai

"Duncan Smith" <buzzard at urubu.freeserve.co.uk> wrote in message news:<bbsq5k$r9j$1 at newsg3.svr.pol.co.uk>...
> "Rogue9" <rogue9 at ntlworld.com> wrote in message news:3ee1e6f1 at shknews01...
> > Pardon me but could anyone enlighten me if python2.2 has a math function
> > to call to do factorials of integers?If not then is there a code snippet
> > for doing such a thing available?I tried to write some code for this
> > myself but with little success.
> > Thanks
> > Lol
> 
> I tend to use gmpy for factorials / combinations and such-like.  But you
> could use something like...
> 
> >>> def fac(n):
> ...  if n == 0:
> ...   return 1
> ...  else:
> ...   return n * fac(n-1)
> ...
> >>> fac(20)
>  2432902008176640000L
> >>>
> 
> Duncan




More information about the Python-list mailing list