[Tutor] A small (but long) introduction to recursion
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Wed, 25 Jul 2001 09:25:54 -0700 (PDT)
On Wed, 25 Jul 2001, Danny Yoo wrote:
> > def addUpToNRecursive(n):
> > if n == 0: return 0
> > print n
> > return addUpToNRecursive(n-1) + n
> >
> > x = addUpToNRecursive(10)
> > print x
If it helps, try this version of the program:
###
def addUpToN(n):
if n == 0: return 0
print (' ' * n) + "Trying to figure out addUpToN(%s)" % n
answer = addUpToN(n-1) + n
print (' ' * n) + "The answer of addUpToN(%s) is %s" % (n, answer)
return answer
###
It's a little bit longer, but it does print something pretty:
###
>>> addUpToN(5)
Trying to figure out addUpToN(5)
Trying to figure out addUpToN(4)
Trying to figure out addUpToN(3)
Trying to figure out addUpToN(2)
Trying to figure out addUpToN(1)
The answer of addUpToN(1) is 1
The answer of addUpToN(2) is 3
The answer of addUpToN(3) is 6
The answer of addUpToN(4) is 10
The answer of addUpToN(5) is 15
15
###