Iteration for Factorials

Tim Chase python.list at tim.thechases.com
Mon Oct 22 16:22:47 EDT 2007


> def fact(x):
>     if x == 0 or x == 1:
>         return 1
>     else:
>         return reduce(operator.mul, xrange(1,x+1))

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)

I haven't yet seen an implementation in C (using the python/C 
interface) or anybody handing off a python AST/opcode-list to an 
appropriate function :)

-tkc






More information about the Python-list mailing list