如何使用python实现的汉诺塔的小程序
时间:2020-06-30 00:24:59
收藏:0
阅读:109
python是面向对象的语言,但是做面向过程的操作,也是得心应手。
代码如下:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from requests.exceptions import RequestException
#定义栈,作为塔的数据结构
class Stack(object):
def __init__(self, name):
self.items = []
self.name = name;
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items) - 1]
def size(self):
return len(self.items)
#定义移动的块
class Block(object):
def __init__(self, size, location):
self.size = size
self.location = location
def setlocation(location):
self.location = location
#移动汉诺塔
def moveblock(s1,s2):
if(s1.size() > 0):
if (s2.size() ==0) or ((s2.size() > 0) and (s2.peek().id > s1.peek().id)):
b = s1.pop()
s2.push(b)
b.location = s2.name
print (b.id, s1.name, "--->", s2.name)
else:
print("can not move")
#显示汉诺塔
def display(s1,s2,s3):
disp(s1)
disp(s2)
disp(s3)
def disp(s):
st=Stack(s.name)
print(s.name)
while(s.size()>0):
b = s.pop()
print(b.id)
st.push(b)
while(st.size()>0):
s.push(st.pop())
#移动汉诺塔
def hanoi(n, a, b, c):
if (n == 1):
moveblock(a, c)
else:
hanoi(n - 1, a, c, b)
moveblock(a, c)
hanoi(n - 1, b, a, c)
#主程序,传入汉诺塔的层高
def main(n):
#定义三个塔
sLeft = Stack("left")
sMiddles = Stack("middle")
sRights = Stack("right")
# 定义n层Block
for i in range(n):
block = Block(n-i,"left")
sLeft.push(block)
display(sLeft, sMiddles, sRights)
hanoi(n, sLeft, sMiddles, sRights)
display(sLeft,sMiddles, sRights)
if __name__ == ‘__main__‘:
main(5)
程序运行结果:
left
1
2
3
4
5
middle
right
1 left ---> right
2 left ---> middle
1 right ---> middle
3 left ---> right
1 middle ---> left
2 middle ---> right
1 left ---> right
4 left ---> middle
1 right ---> middle
2 right ---> left
1 middle ---> left
3 right ---> middle
1 left ---> right
2 left ---> middle
1 right ---> middle
5 left ---> right
1 middle ---> left
2 middle ---> right
1 left ---> right
3 middle ---> left
1 right ---> middle
2 right ---> left
1 middle ---> left
4 middle ---> right
1 left ---> right
2 left ---> middle
1 right ---> middle
3 left ---> right
1 middle ---> left
2 middle ---> right
1 left ---> right
left
middle
right
1
2
3
4
5
评论(0)