Iteration for Factorials

Ant antroy at gmail.com
Mon Oct 22 10:45:48 EDT 2007


On Oct 22, 1:26 pm, 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.

The following simple adder functions should give you an idea of how
recursion can be recast as iteration:

def acc(i):
    '''i should be a positive integer'''
    if i > 0:
        return i + acc(i - 1)
    return 0

print "acc", acc(9)

def itt(i):
    '''i should be a positive integer'''
    out = 0

    while i > 0:
        out += i
        i = i - 1

    return out

print "itt", itt(9)

> ...
> Is it a "factorial" though?

Er, no. And neither is mine. You may want to google for the definition
of factorial! Here's a hint:

reduce(operator.mul, range(1, i + 1))

--
Anthony Roy





More information about the Python-list mailing list