How on Factorial
stefan_ml at behnel.de
Thu Oct 28 19:48:14 CEST 2010
karmaguedon, 28.10.2010 18:46:
> On 27 oct, 10:27, Arnaud Delobelle wrote:
>> Chris Rebert writes:
>>> On Tue, Oct 26, 2010 at 11:25 PM, Geobird 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
>> 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!
> I didn't know the idiom, nice tip.
Not really. Given that many people won't know it, most readers will have a
hard time deciphering the above code, so it's best not to do this.
More information about the Python-list