Back to Freecodecamp

Step 53

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

latest1.1 KB
Original Source

--description--

Although recursion can sometimes be less easy to understand, it gives you the power to create more concise code. In this case, you don't even need to differentiate between even and odd numbers of disks.

Set NUMBER_OF_DISKS to 5 and check the output.

--hints--

You should set the NUMBER_OF_DISKS variable to 5.

js
({test: () => assert.equal(__userGlobals.get('NUMBER_OF_DISKS'), 5) })

--seed--

--seed-contents--

py
--fcc-editable-region--
NUMBER_OF_DISKS = 4
A = list(range(NUMBER_OF_DISKS, 0, -1))
B = []
C = []

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, target, auxiliary)
        
        # move the nth disk from source to target
        target.append(source.pop())
        
        # display our progress
        print(A, B, C, '\n')
        
        # move the n - 1 disks that we left on auxiliary onto target
        move(n - 1,  auxiliary, source, target)
              
# initiate call from source A to target C with auxiliary B
move(NUMBER_OF_DISKS, A, B, C)
--fcc-editable-region--