Skip to content

Instantly share code, notes, and snippets.

@laat
Created November 17, 2010 16:56
Show Gist options
  • Save laat/703642 to your computer and use it in GitHub Desktop.
Save laat/703642 to your computer and use it in GitHub Desktop.
Solves towers of hannoi
# coding=utf-8
'''
File: hanoi.py
Author: Sigurd Fosseng, Håkon Røkenes
Description: Solves towers of hanoi
http://en.wikipedia.org/wiki/Tower_of_Hanoi#Simpler_statement_of_iterative_solution
'''
def legal_move(m, n):
if len(m) > 0 and len(n) > 0:
if m[0] > n[0]:
m.insert(0, n.pop(0))
else:
n.insert(0, m.pop(0))
elif len(m) > 0:
n.append(m.pop(0))
else:
m.append(n.pop(0))
return (m, n)
def main():
a = [1, 2, 3, 4, 5, 6, 7]
b = []
c = []
pairs = len(a) % 2
orig_num = len(a)
if pairs == 0:
while(len(c) != orig_num):
a, b = legal_move(a, b)
a, c = legal_move(a, c)
b, c = legal_move(b, c)
if pairs == 1:
while(len(c) != orig_num):
a, c = legal_move(a, b)
a, b = legal_move(a, c)
b, c = legal_move(b, c)
print c
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment