I am trying to implement Tower of Hanoi using recursion with my own approach. I don't know if it is a valid solution at all. But it definitely works 1, 2, and 3 disks. In fact, given a number of disks more than 3, it gives the right moves for exactly the first 10 steps. I tried but couldn't figure it out. I want to know what is wrong with my code, and I appreciate it if you could spend some of your time on it.
#The `solver` tries to modify the `moves` global variable to include the correct sequence of
#moves to be made. Example output: moves -> [(0,1), (0,2), (1,2)] for 2 disks (num_disks = 2)
def solver (start, source, target):
if start[source] == 1:
start[source] -= 1
start[target] += 1
moves.append((source, target))
return start
else:
start[source] -= 1
target = 3 - (source+target)
start = solver(start, source, target)
start[source] += 1
target = 3 - (source+target)
start = solver(start, source, target)
source = 3 - (source+target)
start = solver(start, source, target)
return start
def convert_to_stack_sizes_and_pass_to_solver (start, source, target):
stack_sizes = [len(start[0]), len(start[1]), len(start[2])]
solver(stack_sizes, source, target)
num_disks = 3
all_disks = list(range(0, num_disks))
moves = []
starting_stacks = [all_disks, [], []]
convert_to_stack_sizes_and_pass_to_solver (starting_stacks, 0, 2)
print(moves)
#Please look at 'moves' variable for output, after execution.
Tried debugging with VS code, but recursion is too counter-intuitive for me for that. You can run the code as is and get the output for up to 3 disks.