汉诺塔问题
1 import turtle 2 3 class Stack: 4 def __init__(self): 5 self.items = [] 6 def isEmpty(self): 7 return len(self.items) == 0 8 def push(self, item): 9 self.items.append(item) 10 def pop(self): 11 return self.items.pop() 12 def peek(self): 13 if not self.isEmpty(): 14 return self.items[len(self.items) - 1] 15 def size(self): 16 return len(self.items) 17 18 def drawpole_3():#画出汉诺塔的poles 19 t = turtle.Turtle() 20 t.hideturtle() 21 def drawpole_1(k): 22 t.up() 23 t.pensize(10) 24 t.speed(100) 25 t.goto(200*(k-1), 100) 26 t.down() 27 t.goto(200*(k-1), -100) 28 t.goto(200*(k-1)-20, -100) 29 t.goto(200*(k-1)+20, -100) 30 drawpole_1(0)#画出汉诺塔的poles[0] 31 drawpole_1(1)#画出汉诺塔的poles[1] 32 drawpole_1(2)#画出汉诺塔的poles[2] 33 34 def creat_plates(n):#制造n个盘子 35 plates=[turtle.Turtle() for i in range(n)] 36 for i in range(n): 37 plates[i].up() 38 39 plates[i].hideturtle() 40 plates[i].shape("square") 41 plates[i].shapesize(1,8-i) 42 plates[i].goto(-200,-90+20*i) 43 plates[i].showturtle() 44 return plates 45 46 def pole_stack():#制造poles的栈 47 poles=[Stack() for i in range(3)] 48 return poles 49 50 def moveDisk(plates,poles,fp,tp):#把poles[fp]顶端的盘子plates[mov]从poles[fp]移到poles[tp] 51 mov=poles[fp].peek() 52 plates[mov].goto((fp-1)*200,150) 53 plates[mov].goto((tp-1)*200,150) 54 l=poles[tp].size()#确定移动到底部的高度(恰好放在原来最上面的盘子上面) 55 plates[mov].goto((tp-1)*200,-90+20*l) 56 57 def moveTower(plates,poles,height,fromPole, toPole, withPole):#递归放盘子 58 if height >= 1: 59 moveTower(plates,poles,height-1,fromPole,withPole,toPole) 60 moveDisk(plates,poles,fromPole,toPole) 61 poles[toPole].push(poles[fromPole].pop()) 62 moveTower(plates,poles,height-1,withPole,toPole,fromPole) 63 64 myscreen=turtle.Screen() 65 drawpole_3() 66 n=int(input("请输入汉诺塔的层数并回车:\n"))#修改汉诺塔的层数 67 plates=creat_plates(n) 68 poles=pole_stack() 69 for i in range(n): 70 poles[0].push(i) 71 moveTower(plates,poles,n,0,2,1) 72 myscreen.exitonclick()