Iteration for Factorials

Rafael Sachetto rsachetto at gmail.com
Mon Oct 22 15:38:33 EDT 2007


This works:

def fact(x):
    if x == 0 or x == 1:
        return 1
    else:
        return reduce(operator.mul, xrange(1,x+1))

or

def factorial(n):

    acc = 1

    while n > 1:
      acc = acc * n
      n = n - 1

    return acc

On 10/22/07, mensanator at aol.com <mensanator at aol.com> wrote:
>
> On Oct 22, 1:35 pm, Paul Rudin <paul.nos... at rudin.co.uk> wrote:
> > "mensana... at aol.com" <mensana... at aol.com> writes:
> > > On Oct 22, 7:50 am, Duncan Booth <duncan.bo... at invalid.invalid> wrote:
> > >> Py-Fun <lorna.bu... at gmail.com> 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.
> >
> > >> This version avoids doing anything fancier than adding 1, so it
> should be
> > >> simple enough for anyone:
> >
> > >> def factorial(e):
> > >>     a = 1
> > >>     for b in range(e):
> > >>         c = 0
> > >>         for j in range(b, -1, -1):
> > >>             for d in range(a):
> > >>                 c += 1
> > >>         a = c
> > >>     return a
> >
> > > Not simple enough for my taste:
> >
> > >>>> import gmpy
> > >>>> gmpy.fac(10)
> > > mpz(3628800)
> >
> > I haven't followed all this thread, but has anyone yet done:
> >
> > import operator
> > def fact(x):
> >     return reduce(operator.mul, xrange(1,x))
>
> I hope not.
>
> >>> import operator
> >>> def fact(x):
>         return reduce(operator.mul,xrange(1,x))
>
> >>> fact(3)
> 2
> >>> fact(2)
> 1
> >>> fact(1)
>
> Traceback (most recent call last):
>   File "<pyshell#10>", line 1, in <module>
>     fact(1)
>   File "<pyshell#7>", line 2, in fact
>     return reduce(operator.mul,xrange(1,x))
> TypeError: reduce() of empty sequence with no initial value
>
> >>> fact(0)
>
> Traceback (most recent call last):
>   File "<pyshell#11>", line 1, in <module>
>     fact(0)
>   File "<pyshell#7>", line 2, in fact
>     return reduce(operator.mul,xrange(1,x))
> TypeError: reduce() of empty sequence with no initial value
>
> I think you need to make it a bit more complicated.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Rafael Sachetto Oliveira

Sir - Simple Image Resizer
http://rsachetto.googlepages.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20071022/608603c7/attachment.html>


More information about the Python-list mailing list