Learn Recursion by Solving the Tower of Hanoi Puzzle - Step 27

Tell us what’s happening:

Can anyone help with this step? I don’t understand what’s wrong with my codes?

Your code so far

NUMBER_OF_DISKS = 3
number_of_moves = 2**NUMBER_OF_DISKS - 1
rods = {
    'A': list(range(NUMBER_OF_DISKS, 0, -1)),
    'B': [],
    'C': []
}

def move(n, source, auxiliary, target):
    # display starting configuration
    print(rods)
    for i in range(number_of_moves):
        remainder = (i + 1) % 3
        if remainder == 1:
            print(f'Move {i + 1} allowed between {source} and {target}')
            forward = False
            if not rods[target]:
                forward = True
            elif rods[source] and rods[source][-1] < rods[target][-1]:
                forward = True

# User Editable Region

            if forward:
                print(f'Moving disk {rods[source][-1]} from {source} to {target}')
                rods[target].append(rods[source].pop())
            else:
                print(f'Moving disk {rods[target][-1]} from {target} to {source}')

# User Editable Region

        elif remainder == 2:
            print(f'Move {i + 1} allowed between {source} and {auxiliary}')
        elif remainder == 0:
            print(f'Move {i + 1} allowed between {auxiliary} and {target}')

# initiate call from source A to target C with auxiliary B
move(NUMBER_OF_DISKS, 'A', 'B', 'C')

Your browser information:

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

Challenge Information:

Learn Recursion by Solving the Tower of Hanoi Puzzle - Step 27

Please describe how the instructions or error message is confusing you. Thanks

Hi @Yuxiao

You should remove the last element from rods[target] .

Here is a comparison of the original code and your code.

The code in blue is the original code, the code in red is your code.
The code in magenta is the overlap.

Happy coding


I think my code is same with the hint, so I am so confused! I don’t understand!

and change the content of the lists accordingly.

The hint isn’t great here. You’re missing the second part of this sentence here

I think you also need to updated the lists to reflect that a disk is moving. In the “if” statement, you do a print command and then use pop and append to move a disk from source to target. I think you now have to do something similar in the “else” statement. Notably though, in the “if” statement, you are moving a disk from source to target. Based on the print statement in your “else” clause, you seem to be moving from target to source. So you would have to modify your pop and append commands above to reflect the different direction in the else clause.