Skip to content

Instantly share code, notes, and snippets.

@shogonir
Created February 14, 2017 15:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shogonir/e68fd36b0523034334668024a9c98568 to your computer and use it in GitHub Desktop.
Save shogonir/e68fd36b0523034334668024a9c98568 to your computer and use it in GitHub Desktop.
#! /usr/bin/env python
# -*- coding:utf-8 -*-
def display_towers(towers):
for i in range(3):
tower_string = ', '.join(['{0:2d}'.format(num) for num in towers[i]])
print 'tower {0} | {1}'.format(i, tower_string)
print
def move_tower(from_pos, to_pos, height, towers):
steps = 0
if height == 1: # base case
tmp = towers[from_pos].pop()
towers[to_pos].append(tmp)
display_towers(towers)
steps += 1
else: # recurse case
tmp_to = [i for i in range(3) if i not in [from_pos, to_pos]][0]
steps += move_tower(from_pos, tmp_to, height - 1, towers)
steps += move_tower(from_pos, to_pos, 1, towers)
steps += move_tower(tmp_to, to_pos, height - 1, towers)
return steps
def solve_hanoi(height):
if height < 1:
print 'Error unexpected arguments exception'
return 0
towers = [
[height - i for i in range(height)],
[],
[]
]
display_towers(towers)
return move_tower(0, 2, height, towers)
if __name__ == '__main__':
total_steps = solve_hanoi(5)
if total_steps != 0:
print 'total {0} steps'.format(total_steps)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment