Back to Freecodecamp

Step 23

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

latest1.9 KB
Original Source

--description--

When target is empty, the disk should be moved necessarily from source to target.

After the declaration of forward, add an if statement to check if rods[target] is empty. If it is, change forward to True.

--hints--

You should have an if statement to check if rods[target] is empty, and assign True to forward.

js
({
    test: () => {
        const tCode = code.replace(/\r/g, '');
        const ifBlock = __helpers.python.getBlock(tCode, "if remainder == 1");
        const { block_body } = ifBlock
        const if2 = __helpers.python.getBlock(block_body, /if [^:]+/);
        const if2Indent = if2.block_body.match(/ +/)[0];
        const ifLoc = tCode.indexOf(block_body.slice(0,20));
        const ifLen = block_body.length;
        const newIf = block_body + `\n${if2Indent}__spy(forward)`
        const newCode = `
__counter = 0
def __spy(x):
    global __counter
    if x:
        __counter += 1

${tCode.slice(0,ifLoc)}
${newIf}
${tCode.slice(ifLoc + ifLen)}

__counter
`;
        const out = runPython(newCode);
        assert.equal(out, 3);
    }
})

--seed--

--seed-contents--

py
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
--fcc-editable-region--
        if remainder == 1:
            print(f'Move {i + 1} allowed between {source} and {target}')
            forward = False
--fcc-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')