Back to Freecodecamp

Step 16

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

latest1.7 KB
Original Source

--description--

At the end of this project, you will create a recursive solution to the Tower of Hanoi puzzle, but now you are going to explore an iterative approach to this problem.

Start by adding a for loop to your function that iterates through the number_of_moves and prints the current iteration number.

--hints--

You should write a for loop to iterate through the number of moves. Use the range() function for that.

js
({ test: () => {
    const rgs = [
        /for\s+\w+\s+in\s+range\s*\(\s*number_of_moves\s*\)\s*:/,
        /for\s+\w+\s+in\s+range\s*\(\s*0\s*,\s*number_of_moves\s*\)\s*:/,
        /for\s+\w+\s+in\s+range\s*\(\s*0\s*,\s*number_of_moves\s*,\s*1\s*\)\s*:/
    ]
    const loop = rgs.some(r => code.match(r));
    assert.isTrue(loop);
  }
})

You should print the current move number at each iteration.

js
({ test: () => {
    const rgs = [
        /for\s+(\w+)\s+in\s+range\s*\(\s*number_of_moves\s*\)\s*:\s+print\s*\(\s*\1\s*\)/,
        /for\s+(\w+)\s+in\s+range\s*\(\s*0\s*,\s*number_of_moves\s*\)\s*:\s+print\s*\(\s*\1\s*\)/,
        /for\s+(\w+)\s+in\s+range\s*\(\s*0\s*,\s*number_of_moves\s*,\s*1\s*\)\s*:\s+print\s*\(\s*\1\s*\)/
    ]
    const loop = rgs.some(r => code.match(r));
    assert.isTrue(loop);
  }
})

--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': []
}

--fcc-editable-region--
def move(n, source, auxiliary, target):
    # display starting configuration
    print(rods)
--fcc-editable-region--

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