This notebook was prepared by [Donne Martin](http://donnemartin.com). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges).

Solution Notebook

Problem: Implement the Towers of Hanoi with 3 towers and N disks.

Constraints

  • Can we assume we already have a stack class that can be used for this problem?
    • Yes

Test Cases

  • None tower(s)
  • 0 disks
  • 1 disk
  • 2 or more disks

Algorithm

  • Create three stacks to represent each tower
  • def hanoi(n, src, dest, buffer):
    • If 0 disks return
    • hanoi(n-1, src, buffer)
    • Move remaining element from src to dest
    • hanoi(n-1, buffer, dest)

Complexity:

  • Time: O(2^n)
  • Space: O(m) where m is the number of recursion levels

Code


In [1]:
%run ../../stacks_queues/stack/stack.py

In [2]:
def hanoi(num_disks, src, dest, buff):
    if src is None or dest is None or buff is None:
        return
    if num_disks > 0:
        hanoi(num_disks-1, src, buff, dest)
        data = src.pop()
        dest.push(data)
        hanoi(num_disks-1, buff, dest, src)

Unit Test


In [3]:
%%writefile test_hanoi.py
from nose.tools import assert_equal


class TestHanoi(object):

    def test_hanoi(self):
        num_disks = 3
        src = Stack()
        buff = Stack()
        dest = Stack()

        print('Test: None towers')
        hanoi(num_disks, None, None, None)

        print('Test: 0 disks')
        hanoi(num_disks, src, dest, buff)
        assert_equal(dest.pop(), None)

        print('Test: 1 disk')
        src.push(5)
        hanoi(num_disks, src, dest, buff)
        assert_equal(dest.pop(), 5)

        print('Test: 2 or more disks')
        for i in range(num_disks, -1, -1):
            src.push(i)
        hanoi(num_disks, src, dest, buff)
        for i in range(0, num_disks):
            assert_equal(dest.pop(), i)

        print('Success: test_hanoi')


def main():
    test = TestHanoi()
    test.test_hanoi()


if __name__ == '__main__':
    main()


Overwriting test_hanoi.py

In [4]:
%run -i test_hanoi.py


Test: None towers
Test: 0 disks
Test: 1 disk
Test: 2 or more disks
Success: test_hanoi