On Oct 22, 3:22 pm, Tim Chase <[EMAIL PROTECTED]> wrote: > > 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)
Indeed. Particularly since it doesn't work: -2! = -2 -1! = -1 0! = 0 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 7! = 5040 8! = 40320 9! = 362880 0! is defined to be 1. You'll have a hard time calculating combinations if 0! returns 0. Also, fact() should raise an exception when x is negative. It not only has to work correctly, it has to fail correctly also. > > 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 -- http://mail.python.org/mailman/listinfo/python-list