AndreiL
Welcome to AndreiL.
Enjoy your time.
Please log in.

Solving Hanoi problem algorithm - Pyhon

Go down

Solving Hanoi problem algorithm - Pyhon

Post by Lucaci Andrei on Wed Feb 22, 2012 10:36 pm

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
'''
Created on Feb 23, 2012

@author: sin
'''

def hanoi(n, x=None, y=None, z=None, fl=None):
fh = open(fl, 'a')
if n == 1:
print "Move disc from", x, 'to', str(y) + '.'
fh.write(("Move disc from tower " + str(x) + ' to tower ' + str(y) + '.\n'))

else:
hanoi(n - 1, x, z, y, fl)
print "Move disc from", x, 'to', str(y) + '.'
fh.write(("Move disc from tower " + str(x) + ' to tower ' + str(y) + '.\n'))
hanoi(n - 1, z, y, x, fl)
fh.close()

print """ Objective:
You have 3 towers, and on your first tower, the x one, are 'n' numbers
of discs, sorted descending, meaning on the top of the stack is the smallest,
and at the bottom is the largest.
Your objective is to move the discs from tower x to tower y, and
place them in the same order they were on tower x, with 1 mover per turn,
using tower z as a tower helper, and of course, determine the smallest
amount of moves.
"""
def main():
fln = raw_input("Name of the file: ") + '.txt'
try:
n = int(raw_input("Number of discs: "))
except:
print "Invalid number of discs.\nGot string, needed integer."
raw_input("Press <<ENTER>> to exit...")
exit()
else:
fh = open(fln, 'w')
fh.write('')
fh.close()
hanoi(n, 'x', 'y', 'z', fln)
print "You now can check", fln, "for your results, if you can't follow on this"
print"console."

if __name__ == '__main__':
main()
raw_input("Press <<ENTER>> to exit...")

avatar
Lucaci Andrei
"Tata Lor"


Number of messages : 222
Points : 2266743
Reputation : 1007
Registration date : 2008-08-15
Age : 25
Location : Cluj-Napoca

View user profile http://www.andreil.wgz.ro

Back to top Go down

Back to top


 
Permissions in this forum:
You cannot reply to topics in this forum