Back to Freecodecamp

Step 24

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

latest2.5 KB
Original Source

--description--

The other case in which you have to move the disk necessarily from source to target is when the source list is not empty and the last disk in source is lower than the last disk in target.

Add an elif statement to check this condition. Then, set the forward variable to True if the condition is met.

--hints--

You should have an elif statement to check if rods[source] is not empty and rods[source][-1] < rods[target][-1].

js
const allowedRes = [
    "rods\\s*\\[\\s*source\\s*\\]",
    "len\\(rods\\s*\\[\\s*source\\s*\\]\\s*\\)\\s*>\\s*0",
    "len\\(rods\\s*\\[\\s*source\\s*\\]\\s*\\)\\s*>=\\s*1",
];
const re = new RegExp(`elif\\s+((${allowedRes.join(")|(")}))\\s+and\\s+(rods\\s*\\[\\s*source\\s*\\]\\s*\\[\\s*-\\s*1\\s*\\]\\s*<\\s*rods\\s*\\[\\s*target\\s*\\]\\s*\\[\\s*-\\s*1\\s*\\]|rods\\s*\\[\\s*target\\s*\\]\\s*\\[\\s*-\\s*1\\s*\\]\\s*>\\s*rods\\s*\\[\\s*source\\s*\\]\\s*\\[\\s*-\\s*1\\s*\\])\\s*:`);
assert.match(code, re);

You should set forward to True inside your new elif statement. You should not change the previous assignments of forward.

js
const allowedRes = [
    "rods\\s*\\[\\s*source\\s*\\]",
    "len\\(rods\\s*\\[\\s*source\\s*\\]\\s*\\)\\s*>\\s*0",
    "len\\(rods\\s*\\[\\s*source\\s*\\]\\s*\\)\\s*>=\\s*1",
];
const re = new RegExp(`elif\\s+((${allowedRes.join(")|(")}))\\s+and\\s+(rods\\s*\\[\\s*source\\s*\\]\\s*\\[\\s*-\\s*1\\s*\\]\\s*<\\s*rods\\s*\\[\\s*target\\s*\\]\\s*\\[\\s*-\\s*1\\s*\\]|rods\\s*\\[\\s*target\\s*\\]\\s*\\[\\s*-\\s*1\\s*\\]\\s*>\\s*rods\\s*\\[\\s*source\\s*\\]\\s*\\[\\s*-\\s*1\\s*\\])\\s*:\\s+forward\\s*=\\s*True`);
assert.match(code, re);

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