# Iterative vs. Recursive coding

Martin Gregorie martin at address-in-sig.invalid
Fri Aug 20 00:00:16 CEST 2010

```On Thu, 19 Aug 2010 14:12:44 -0700, Baba wrote:

> Level: Beginner
>
> exercise source:
> http://ocw.mit.edu/courses/electrical-engineering-and-computer-
science/6-00-introduction-to-computer-science-and-programming-fall-2008/
assignments/pset3.pdf
>
> I am looking at the first problem in the above assignment. The
> assignemnt deals, amongst others, with the ideas of iterative vs.
> recursive coding approaches and i was wondering what are the advantages
> of each and how to best chose between both options?
>
> I had a go at the first part of the exercise and it seems that i can
> handle it. However i think my Recursive version can be improved. By the
> way, is my code actually proper recursive code?
>
No, it isn't.

By way of a hint, here are two versions of the classic example of
recursion: calculating factorials. Recursion can be quite a trick to get
your mind round at first, so compare the two and follow through their
operation step by step...

-------------------------------------------------

def i_factorial(n):
"Iterative factorial calculation"
f = 1;
for n in range(1, n+1):
f = f * n
return f

def r_factorial(n):
"Recursive factorial calculation"
if (n > 1):
return n * r_factorial(n - 1)
else:
return 1

print i_factorial.__doc__
for n in range(1,10):
print "%d! = %d" % (n, i_factorial(n))

print r_factorial.__doc__
for n in range(1,10):
print "%d! = %d" % (n, r_factorial(n))

-----------------------------------------

In case you're wondering "print i_factorial.__doc__"
prints the docstring out of the i_factorial subroutine.
You probably haven't covered that yet, but run it and see.

--
martin@   | Martin Gregorie
gregorie. | Essex, UK
org       |

```

More information about the Python-list mailing list