Iteration for Factorials

J. Clifford Dyer jcd at sdf.lonestar.org
Tue Oct 30 09:13:39 EDT 2007


On Tue, Oct 30, 2007 at 01:09:38PM +0100, Boris Borcic wrote regarding Re: Iteration for Factorials:
> 
> Py-Fun wrote:
> > I'm stuck trying to write a function that generates a factorial of a
> > number using iteration and not recursion.  Any simple ideas would be
> > appreciated.
> > 
> 
> fact = lambda n : len(map([1].__imul__,range(1,n+1))[0])
> 
> hth :)
> 

Nice one.  I was trying to grok it, and started out by breaking it down:

>>> [1].__imul__(2)
[1, 1]
>>> map([1].__imul__,range(1,3))
[[1, 1], [1, 1]]

So far so good, but I tried to break it down a little more:

>>> [1].__imul__(1), [1].__imul__(2), [1].__imul__(3)
([1], [1, 1], [1, 1, 1])

Hmm.  Wasn't what I was expecting.

Then it hit me:

>>> L = [1]
>>> L.__imul__(1), L.__imul__(2), L.__imul__(3)
([1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1])

Pretty sneaky, sis.

Cheers,
Cliff

P.S.  Regards to those who lack a grounding in American pop-culture, or who are to young to remember the origins of "Pretty sneaky, sis."



More information about the Python-list mailing list