Back to Freecodecamp

Step 46

curriculum/challenges/english/blocks/learn-recursion-by-solving-the-tower-of-hanoi-puzzle/64df45a3ad4f8719e5355244.md

latest2.1 KB
Original Source

--description--

The steps of moving n - 1 disks can be broken down further until only a single disk is considered. This will be the first move occurring. After the first move occurs, the following moves are generated by the unwinding of the recursive calls. Keep in mind that in each recursive step the role played by the rods changes between source, target, and auxiliary.

For now, each recursive call prints the rods dictionary without performing any changes to the lists. Before the print() call, remove the last element from the rods[source] list and append it to the rods[target] list.

--hints--

You should remove the last element from the rods[source] list and append it to the rods[target] list before the print call.

js
({ test: () => assert.isTrue(runPython(`
_log = []
def capture_print(*args):
    _log.append(repr(args))

old_print = print
print = capture_print

old_rods = rods
rods2 = {
    'A': list(range(5, 0, -1)),
    'B': [],
    'C': []
}
rods = rods2

move(5, 'A', 'B', 'C')
rods = old_rods
print = old_print

_expected_prints = [
r"({'A': [5, 4, 3, 2], 'B': [], 'C': [1]}, '\\n')",
r"({'A': [5, 4, 3], 'B': [], 'C': [1, 2]}, '\\n')",
r"({'A': [5, 4], 'B': [], 'C': [1, 2, 3]}, '\\n')",
r"({'A': [5], 'B': [], 'C': [1, 2, 3, 4]}, '\\n')",
r"({'A': [], 'B': [], 'C': [1, 2, 3, 4, 5]}, '\\n')",
]

for args in _log:
    if not _expected_prints:
        break
    if args == _expected_prints[0]:
        _expected_prints.pop(0)

not rods2['A'] and rods2['C'] == list(range(1, 6)) and not _expected_prints
`))})

--seed--

--seed-contents--

py
NUMBER_OF_DISKS = 4
rods = {
    'A': list(range(NUMBER_OF_DISKS, 0, -1)),
    'B': [],
    'C': []
}

--fcc-editable-region--
def move(n, source, auxiliary, target):
    if n > 0:
        # move n - 1 disks from source to auxiliary, so they are out of the way
        move(n - 1, source, auxiliary, target)
        
        # display starting configuration
        print(rods, '\n')
              
--fcc-editable-region--
# initiate call from source A to target C with auxiliary B
move(NUMBER_OF_DISKS, 'A', 'B', 'C')