Implement the Tower of Hanoi Algorithm - Implement the Tower of Hanoi Algorithm

Tell us what’s happening:

I am baffled. My code implements the algorithm, I am confident, but what is printed is different. I suspect this lies in the function calls, but I can’t find the combination. I have printed results in detail, and that has not yielded a result. I think I understnd recursion, but it is difficult to track in details. Is there an execution line by line trace that I can use? I think that would help.

Your code so far

def hanoi_solver(size):
    moves = ''
    A = list(range(size,0,-1))
    B = []
    C = []

    def tower(dim,src,ax,dst):
        nonlocal moves
        if dim == 1:
            dst.append(src.pop())
            moves += f"{src} {ax} {dst} {dim} one\n"
            return

        tower(dim-1,src,dst,ax)
        dst.append(src.pop())
        moves += f"{src} {ax} {dst} {dim} else\n"
        tower(dim-1,ax,src,dst)
        return

    moves += f"{A} {B} {C}start\n"
    tower(size,A,B,C)
    return moves

#print(hanoi_solver(1))
print(hanoi_solver(2))
print(hanoi_solver(3))


Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64; rv:148.0) Gecko/20100101 Firefox/148.0

Challenge Information:

Implement the Tower of Hanoi Algorithm - Implement the Tower of Hanoi Algorithm

Hi @delkimbler ,

Try this: Python Code Visualizer

Happy coding!

Thanks! That visualizer let me track the steps to confirm that I had the algorithm moves correct, but recorded them according to the shifting names rather than absolute stacks.

Thanks for sharing this link it helps me also