# Iteration for Factorials

mensanator at aol.com mensanator at aol.com
Tue Oct 30 21:15:54 CET 2007

```On Oct 30, 1:52 pm, "J. Clifford Dyer" <j... at sdf.lonestar.org> wrote:
> On Tue, Oct 30, 2007 at 11:37:57AM -0700, mensana... at aol.com wrote regarding Re: Iteration for Factorials:
>
>
>
>
>
>
>
> > On Oct 30, 10:25 am, "J. Clifford Dyer" <j... at sdf.lonestar.org> wrote:
> > > 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])
>
>
> > > def fact(x):
> > >         def f(x):
> > >                 if int(x) != x:
> > >                         raise ValueError
> > >                 elif x > 1:
> > >                         return f(x-1) ** x
> > >                 elif x == 1:
> > >                         return 10
> > >                 else:
> > >                         raise ValueError
> > >         return len(str(f(x))) -1
>
> > > The great part about this recursive solution is that you don't have to worry about the stack limit because performance degrades so quickly on the conversion to string!  fact(8) takes a little less than a second, fact(9) takes about a minute, and fact(10) takes more time than I had patience to wait for!
>
> > And the not-so-great part is that it raises an exception
> > on fact(0) which makes it utterly useless for calculating
> > combinations of m things taken n at a time: m!/n!*(m-n)!
>
> > Why is it that no one seems able to get this right?
>
> I can't speak for everyone, but my excuses are as follows:
>
> * I haven't studied math or done math-heavy work in 8 years.

Fair enough. I primarily do math-heavy work, and am familiar
with such matters. But that's just me.

> * I'm not at my home computer, and most of the thread (wherein,
>   to my home computer, so I was working from my feeble memory.

Well, I've only had to point it out a dozen times already in
this thread. Nice to see that all that effort has been for nought.

> * I didn't care enough to google for it.

Quoting from Monty Python:
"It's just as easy to get these things right, you know."

>
> That said, s/elif x == 1:/elif x in (0,1):/ should solve the problem

Sure, it's always easily solvable. I just hope someone learns the
lesson on how to test properly, to make sure things work the way
they should and to fail the way they should so that one can actually
trust the algorithms they write.

```