Iteration for Factorials

Tim Chase python.list at tim.thechases.com
Mon Oct 22 18:39:58 EDT 2007


>> 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:

>>> 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