0

I'm trying to do a substitution trace for this code:

def hanoi(n):
   if n == 1:
       return 1
   else:
       return 2 * hanoi(n - 1) + 1

print hanoi(4)

Output:

15

This is what I did:

2 * (4 - 1) + 1

2 * (3) + 1

6 + 1

7

I'm not sure what I'm doing wrong.

2 Answers 2

3

You have a recursion function and after each step it converted to sub functions with n-1 : Actually you have this :

2 * hanoi(4 - 1) + 1
2 * hanoi(3) + 1
2 * (2 * hanoi(2) + 1) + 1
2 * (2 * (2 * hanoi(1) + 1) + 1)  + 1
2 * (2 * (2 * 1 + 1) + 1) + 1 = 15
Sign up to request clarification or add additional context in comments.

1 Comment

I understand now. I completely forgot to account for the recursion. Thank you for explaining it and showing how its was done.
0

2 * hanoi(4-1) + 1 is not the same as 2 * (4-1) + 1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.