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

Tell us what’s happening:

my code seems to be returning the correct output, however all output tests are failing - I’ve checked spacings and ensured the last \n is stripped - pls help

Your code so far

def hanoi_solver(n):
    A = list(range(n, 0, -1))
    B = []
    C = []
    end_string = ''
    def move(n, source, aux, target):
        nonlocal end_string
        if n <= 0:
            return
        # move n - 1 disks to middle
        move(n - 1, source, target, aux)
        target.append(source.pop())
        end_string += str(A) + str(B) + str(C) + '\n'

        move(n - 1, aux, source, target)

    end_string += str(A) + str(B) + str(C) + '\n'
    move(n, A, B, C)
    return end_string.strip()

print(hanoi_solver(2))

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36

Challenge Information:

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

For example for one of the cases, this is what function returns:

[2, 1][][]
[2][1][]
[][1][2]
[][][2, 1]

This is what is expected to be returned:

[2, 1] [] []
[2] [1] []
[] [1] [2]
[] [] [2, 1]
1 Like

Thanks - should’ve tried the spacings sooner