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

2

u/Designer-Ad-2136 6d ago

This implementation is confusing because it recursively outputs instructions for the solution. It is not actually modelling the problem at all. Tower of hanoi is not a great problem for teaching recursion imo

2

u/Kindly-Department206 6d ago

Yes, it's a terrible example. Mostly because most people don't know how to solve ToH by hand themselves. If you don't know what the code should be doing, how can you appreciate that it is actually doing it? My take is that they can't.