Back to Freecodecamp

Step 44

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

latest2.3 KB
Original Source

--description--

To solve the puzzle with recursion, the first thing to do is break the original problem down into smaller sub-problems.

The final configuration with n disks piled up to the third rod in decreasing order can be obtained by moving:

  • n - 1 disks from the source to the auxiliary rod
  • the largest disk from the source to the target
  • and then the n - 1 disks from the auxiliary rod to the target.

So, the first thing the move function should do is calling itself with n - 1 as the first argument. But if you try to do so without defining a base case, you will get a RecursionError. This happens because the function keeps calling itself indefinitely.

Before your comment and your print() call, add the recursive function call with n - 1 as the first argument and make sure the function body executes only when n is greater than zero. For now, leave the other arguments in the same order.

--hints--

The move function body should start with an if statement that is triggered when n is greater than zero.

js
({ test: () => assert.match(code, /def\s+move\(\s*n\s*,\s*source\s*,\s*auxiliary\s*,\s*target\s*\)\s*:\s+if\s+n\s*>\s*0\s*:/) })

You should call move(n - 1, source, auxiliary, target) inside the if statement. Remember to indent your print() call.

js
const transformedCode = "\n" + code.replace(/\r/g, '');
const move = __helpers.python.getDef(transformedCode, "move");
const { function_parameters, function_body } = move;

assert.match(function_parameters, /n\s*,\s*source\s*,\s*auxiliary\s*,\s*target/);
const functionBodyIndent = function_body.match(/ +/)[0];
const re = new RegExp(`${functionBodyIndent}if\\s+n\\s*>\\s*0\\s*:\\s+^${functionBodyIndent}( +)move\\(\\s*n\\s*-\\s*1\\s*,\\s*source\\s*,\\s*auxiliary\\s*,\\s*target\\s*\\).+?^${functionBodyIndent}\\1print\\s*\\(\\s*rods\\s*,\\s*("|')\\\\n\\2\\s*\\)`, "ms");
assert.match(function_body, re);

--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):
    # 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')