Created
February 14, 2017 15:55
-
-
Save shogonir/72e7fcd9a2dc126321dc4b1078d87dcd to your computer and use it in GitHub Desktop.
solve tower of hanoi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /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) | |
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