Iteration for Factorials

mensanator at aol.com mensanator at aol.com
Tue Oct 23 19:33:14 CEST 2007


On Oct 23, 5:55 am, Marco Mariani <ma... at sferacarta.com> wrote:
> Tim Chase wrote:
> >>>> fact = lambda i: i > 1 and reduce(mul, xrange(1, i+1)) or not
> > i and 1 or None
>
> > Stunts like this would get a person fired around here if they
> > were found in production code :)
>
> eheh, indeed.
>
> def fact(n):
>      try:
>          return eval('*'.join(str(x) for x in range(1,n+1)))
>      except:
>          return 1

Needs work.

IDLE 1.2
>>> def fact(n):
     try:
         return eval('*'.join(str(x) for x in range(1,n+1)))
     except:
         return 1

>>> fact(3)
6
>>> fact(2)
2
>>> fact(1)
1
>>> fact(0)
1
>>> fact(-1)
1
>>> fact(-2)
1




More information about the Python-list mailing list