Tell us what’s happening:
Hello, I am confused about why my code says hanoi_solver does not return a string.
I have tried isinstance and it returned true.
Thank you for all the time and help. Ik my is probably not great, recursion is hard. I prob should of used iteration instead.
Your code so far
first_ring = []
second_ring = []
third_ring = []
print_message = ''
initialized = False
def pm(source, target):
global print_message, first_ring, second_ring, third_ring
if source == 1:
ring = first_ring.pop()
elif source == 2:
ring = second_ring.pop()
else:
ring = third_ring.pop()
if target == 1:
first_ring.append(ring)
elif target == 2:
second_ring.append(ring)
else:
third_ring.append(ring)
print_message += f'{first_ring} {second_ring} {third_ring} \n'
def solver(n, location = 1, target = 3):
global first_ring, second_ring, third_ring, print_message, initialized
if not initialized:
first_ring = list(range(n, 0, -1))
second_ring = []
third_ring = []
print_message = f'{first_ring} {second_ring} {third_ring} \n'
initialized = True
if n == 1:
pm(location, target)
else:
other = 6 - location - target
solver(n-1, location, other)
pm(location, target)
solver(n-1, other, target)
def hanoi_solver(n):
solver(n)
return str(print_message.rstrip('\n'))
print(hanoi_solver(4))
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Safari/537.36
Challenge Information:
Implement the Tower of Hanoi Algorithm - Implement the Tower of Hanoi Algorithm