0

I have this simple code using recursion that calculates the exponent. I understand how the recursion works here except for the: if exp <= 0: return 1. Say I call the function to give me five to the second power. If I have it return 1, it will give me the correct value of 25, but if 2 it returns 50, and 3, 75.

I am having a little trouble seeing how exactly this works within the environment:

def recurPower(base,exp):
    if exp <= 0:
        return 1
    return base*recurPower(base,exp-1)

print str(recurPower(5,2))
Blckknght
  • 100,903
  • 11
  • 120
  • 169
Tom Lilletveit
  • 1,872
  • 3
  • 31
  • 57
  • The code looks right. I'm puzzled by your description of 5^2. It doesn't look like the code will do anything wrong. – sashang Oct 18 '12 at 03:14

2 Answers2

4

I'm not sure if I understand the question. The 1 in the base case is there it is base^0 (for any non-zero base) and also because it is the multiplicative identity, so you can freely multiply by it.

It might help you try "unrolling" the recursion, to see where the numbers go:

recurPower(5, 2) = 
5 * recurPower(5, 1) = 
5 * 5 * recurPower(5, 0) =
5 * 5 * 1 =
25

Putting 2 or 3 in place of the 1 gets you two or three times the exponent you are trying to calculate.

Blckknght
  • 100,903
  • 11
  • 120
  • 169
2

whats happening here, is you'll end up with a cascade of returning values that will start with the value which is returned by that return 1 statement, for example:

recurPower(5,2) == 
recurPower(5,2) -> recurPower(5,1) -> recurPower(5,0)

the return statements will then make this:

1 -> (1)*5 -> (5)*5 

(in reverse of the previous chain since we're cascading up the chain).

if you change the return value to 2 you will get:

2 -> (2)*5 -> (10)*5 

(in reverse of the previous chain since we're cascading up the chain).

Numbers in brackets are returned from lower down the recursion chain.

Serdalis
  • 10,296
  • 2
  • 38
  • 58