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

Tell us what’s happening:

IndexError: pop from empty list

I got this error in console. Please help me to solve issue.

Your code so far

def hanoi_solver(n):
    rods = [list(range(n, 0, -1)), [], []]
    moves = []

    def record():
        moves.append(f"{rods[0]} {rods[1]} {rods[2]}")

    def move(disks, source, target, auxiliary):
        if disks == 1:
            rods[target].append(rods[source].pop())
            record()
            return

        move(disks - 1, source, auxiliary, target)
        rods[target].append(rods[source].pop())
        record()
        move(disks - 1, auxiliary, source, target)

    record()

    move(n, 0, 2, 1)

    return "\n".join(moves)

print(hanoi_solver(5))

Your browser information:

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

Challenge Information:

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

GitHub Link: freeCodeCamp/curriculum/challenges/english/blocks/lab-tower-of-hanoi/68773ee26f332a80bc0295db.md at main · freeCodeCamp/freeCodeCamp · GitHub

You need to change source and target parameter position in the Hanoi algorithm.:grinning_face:

As you can see target is not empty always, and source can be empty.

It’s the reason that you got above error.

Oh, that’s working, thank you very much.