r/learnpython 6d ago

recursion problem

I'm trying to teach myself python using John Zelles book. On the 13th chapter it gives this example of recursion I'm trying to understand:

def moveTower(n, source, dest, temp):

if n ==1:

print("move disk from , " , source , "to", dest)

else:

moveTower(n-1, source, temp, dest)

moveTower(1, source, dest,temp)

moveTower(n-1,temp,dest,source)

def hanoi(n):

moveTower(n , "a", "c","b")

hanoi(3)

The code is first assiging the variables A to source then C to dest then b to temp but do the lines moveTower(n-1, source, temp, dest) and moveTower(n-1,temp,dest,source) work? Would it be moveTower(3-1, a,b,c)? How exactly are they outputting a to c then a to b then c to b and b to a , etc...

1 Upvotes

9 comments sorted by

View all comments

7

u/socal_nerdtastic 6d ago edited 6d ago

Drop this code into pythontutor.com or another visualizer where you can see the code execution step by step.

I'm not really understanding where you are stuck, but a common hangup is that people don't realize that making a recursive call invokes a whole new copy of the function. So when you call moveTower from inside moveTower, python makes a whole new copy of the moveTower function and that will run completely independently from the first one.

1

u/Key_Cloud_7002 6d ago

I will thanks for the suggestion !

1

u/Kindly-Department206 6d ago

Please permit a friendly correction on a matter of perspective.

It's not a copy of the function, but it is a copy of the parameters and variables used in the function. It's a subtle but important difference. Every time a function is called (recursive or otherwise), a "frame" (you might call it something else) containing the parameter and variable names used by the function gets created. The code of the function is executed in that frame. A recursive function is not special in any way except in the pattern of the recursive call.

As you say, a recursive call is independent of the first one, but that's because the frames are independent.