How on Factorial

karmaguedon karmaguedon at gmail.com
Thu Oct 28 18:46:17 CEST 2010


On 27 oct, 10:27, Arnaud Delobelle <arno... at gmail.com> wrote:
> Chris Rebert <c... at rebertia.com> writes:
> > On Tue, Oct 26, 2010 at 11:25 PM, Geobird <a1chan... 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

I didn't know the idiom, nice tip.
thanks



More information about the Python-list mailing list