Skip to content

Instantly share code, notes, and snippets.

@cabiad
Last active December 14, 2015 00:49
Show Gist options
  • Save cabiad/5001889 to your computer and use it in GitHub Desktop.
Save cabiad/5001889 to your computer and use it in GitHub Desktop.
Towers of Hanoi: Python2 implementation both recursively and iteratively using a Python list as our stack. Note that the well-known iterative solution with O(1) space requirements is not included here.
####################################
# Copyright Christopher Abiad, 2013
# All Rights Reserved
####################################
__author__ = 'Christopher Abiad'
def toh(num, src, dest, other):
if num <= 0:
return
elif num == 1:
print "move {s} to {d}".format(s=src, d=dest)
return
toh(num - 1, src, other, dest)
print "move {s} to {d}".format(s=src, d=dest)
toh(num - 1, other, dest, src)
def toh_iterative(num, src, dest, other):
class Move(object):
def __init__(self, num, src, dest, other):
self.num = num
self.src = src
self.dest = dest
self.other = other
if num == 0:
return
work = [Move(num, src, dest, other)]
while len(work) > 0:
item = work.pop()
if item.num == 1:
print "move {s} to {d}".format(s=item.src, d=item.dest)
else:
# Append new work to do in reverse order
# (first thing to do next is appended last)
work.append(Move(item.num - 1, item.other, item.dest, item.src))
work.append(Move(1, item.src, item.dest, item.other))
work.append(Move(item.num - 1, item.src, item.other, item.dest))
if __name__ == '__main__':
print "recursive solution:"
toh(3, 's', 'd', 'o')
print "\niterative solution:"
toh_iterative(3, 's', 'd', 'o')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment