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

Tell us what’s happening:

i dont understand why function dont pass in test 3, function return a string

Your code so far

rod = ['S', 'A', 'D']
stacks = [[], [], []]

def moveDisk(a, b):
    if not stacks[b] or (stacks[a] and stacks[a][-1] < stacks[b][-1]):
        stacks[b].append(stacks[a].pop())
    else:
        moveDisk(b, a)


def hanoi_solver(n):
    moves = ""
    src, aux, dest = 0, 1, 2
    stacks[src] = list(range(n, 0, -1))
    moves = repr(stacks[0]) + repr(stacks[1]) + repr(stacks[2]) + "\n"
    totalMoves = (1 << n) - 1
    if n % 2 == 0:
        aux, dest = dest, aux

    for i in range(1, totalMoves + 1):
        if i % 3 == 0:
            moveDisk(aux, dest)
        elif i % 3 == 1:
            moveDisk(src, dest)
        else:
            moveDisk(src, aux)
        
        moves += repr(stacks[0]) + repr(stacks[1]) + repr(stacks[2]) + "\n"
    return moves.strip('\n')


n = 3  # number of disks
print(hanoi_solver(n))

Your browser information:

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

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

This is what the test runs:

print(isinstance(hanoi_solver(2), str))
print(isinstance(hanoi_solver(6), str))
print(isinstance(hanoi_solver(11), str))

The output returns an error:

True
True
Traceback (most recent call last):
  File "main.py", line 33, in <module>
  File "main.py", line 24, in hanoi_solver
  File "main.py", line 8, in moveDisk
  File "main.py", line 8, in moveDisk
  File "main.py", line 8, in moveDisk
  [Previous line repeated 993 more times]
RecursionError: maximum recursion depth exceeded

So you’re right, your function does return a string, if it does not encounter this error.

how i solve this error?

your function is doing too much recursion, you need to remove unnecessary calls