Iteration for Factorials

mensanator at aol.com mensanator at aol.com
Mon Oct 22 19:20:29 EDT 2007


On Oct 22, 5:39 pm, Tim Chase <python.l... at tim.thechases.com> wrote:
> >> If obscurity is the name of the game,
>
> >>    >>> from operator import mul
> >>    >>> fact = lambda i: i > 1 and reduce(mul, xrange(1,i+1)) or i
> >>  >= 0 and 1 or None
> >>    >>> for i in xrange(-2,10): print '%i! = %s' % (i, fact(i))
>
> >> My eyes hurt after reading that...as the order of operations is
> >> left to Python to discern (a few judiciously placed parens might
> >> improve things...though that may be like polishing coprolite)
>
> > Indeed. Particularly since it doesn't work:
>
> Huh?  Works on the Python (2.4) I have, both the Win32 python at
> work and Linux Python at home:

Sorry about that, Google line wrapped the fact definition
and it worked anyway in Idle (but not as written).

Still, why do you want None instead of raisng an exception
(as is the case in other factorial implementations)?

>
> >>> from operator import mul
> >>> fact = lambda i: i > 1 and reduce(mul, xrange(1, i+1)) or i
> >= 0 and 1 or None
> >>> for i in xrange(-2,10): print '%i! = %s' % (i, fact(i))
>
> ...
> -2! = None
> -1! = None
> 0! = 1
> 1! = 1
> 2! = 2
> 3! = 6
> 4! = 24
> 5! = 120
> 6! = 720
> 7! = 5040
> 8! = 40320
> 9! = 362880
>
> It could even be more obscure by making it
>
> >>> 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 :)
>
> -tkc





More information about the Python-list mailing list