How on Factorial

Arnaud Delobelle arnodel at gmail.com
Wed Oct 27 04:27:21 EDT 2010


Chris Rebert <clp2 at rebertia.com> writes:

> On Tue, Oct 26, 2010 at 11:25 PM, Geobird <a1chandan at gmail.com> wrote:
>>
>>  I  am a beginner in Python and would ask for a help.
>>
>>
>> I  was searching for  smaller  version  of  code  to calculate
>> factorial . Found  this one
>> def fact(x):
>>        return x > 1 and x * fact(x - 1) or 1
>>
>>  But I don't  really get how (  ....x > 1 and x * fact(x - 1)....)
>> works .
>
> It exploits short-circuit evaluation
> (http://en.wikipedia.org/wiki/Short-circuit_evaluation ). This is
> stunt coding / code golf; no one should actually write factorial like
> that.

True.  It's far too verbose.  I'd go for something like:

    f=lambda n:n<=0 or n*f(~-n)

I've saved a few precious keystrokes and used the very handy ~- idiom!

-- 
Arnaud



More information about the Python-list mailing list