1一、漢諾塔五層:mport turtle23
class
stack:
4def
__init__
(self):
5 self.items =
6def
isempty(self):
7return len(self.items) ==0
8def
push(self, item):910
defpop(self):
11return
self.items.pop()
12def
peek(self):
13if
notself.isempty():
14return self.items[len(self.items) - 1]
15def
size(self):
16return
len(self.items)
1718
def drawpole_3():#
畫出漢諾塔的poles
19 t =turtle.turtle()
20t.hideturtle()
21def
drawpole_1(k):
22t.up()
23 t.pensize(10)
24 t.speed(100)
25 t.goto(400*(k-1), 100)
26t.down()
27 t.goto(400*(k-1), -100)
28 t.goto(400*(k-1)-20, -100)
29 t.goto(400*(k-1)+20, -100)
30 drawpole_1(0)#
畫出漢諾塔的poles[0]
31 drawpole_1(1)#
畫出漢諾塔的poles[1]
32 drawpole_1(2)#
畫出漢諾塔的poles[2]
3334
def creat_plates(n):#
製造n個盤子
35 plates=[turtle.turtle() for i in
range(n)]
36for i in
range(n):
37plates[i].up()
38plates[i].hideturtle()
39 plates[i].shape("
square")
40 plates[i].shapesize(1,8-i)
41 plates[i].goto(-400,-90+20*i)
42plates[i].showturtle()
43return
plates
4445
def pole_stack():#
製造poles的棧
46 poles=[stack() for i in range(3)]
47return
poles
4849
def movedisk(plates,poles,fp,tp):#
把poles[fp]頂端的盤子plates[mov]從poles[fp]移到poles[tp]
50 mov=poles[fp].peek()
51 plates[mov].goto((fp-1)*400,150)
52 plates[mov].goto((tp-1)*400,150)
53 l=poles[tp].size()#
確定移動到底部的高度(恰好放在原來最上面的盤子上面)
54 plates[mov].goto((tp-1)*400,-90+20*l)
5556
def movetower(plates,poles,height,frompole, topole, withpole):#
遞迴放盤子
57if height >= 1:
58 movetower(plates,poles,height-1,frompole,withpole,topole)
59movedisk(plates,poles,frompole,topole)
60poles[topole].push(poles[frompole].pop())
61 movetower(plates,poles,height-1,withpole,topole,frompole)
6263 myscreen=turtle.screen()
64drawpole_3()
65 n=int(input("
請輸入漢諾塔的層數並回車:"))
66 plates=creat_plates(n)
67 poles=pole_stack()
68for i in
range(n):
69poles[0].push(i)
70 movetower(plates,poles,n,0,2,1)
71 myscreen.exitonclick()
二、漢諾塔三層:
python 漢諾塔 Python漢諾塔
import turtle class stack def init self self.items def isempty self return len self.items 0 def push self,item def pop self return self.items.pop def ...
python 漢諾塔問題
最近被漢諾塔的python 遞迴給迷暈,本想搞個程式除錯,但sublimetext用的不是很熟,參考了很多大佬的博文,需要總結下以防往後忘記 關於理解 流程,其實主要關注兩點 1 形參實參注意別搞混了 2 函式呼叫後都是要返回的,從哪個入口進去執行最後執行完程式是要返回回原來的入口,再執行時要注意開...
漢諾塔問題(python)
def hanoi n,a,b,c 將n個圓盤從a經過b移到c if n 0 圓盤數大於0 hanoi n 1,a,c,b 將n 1個圓盤從a經過c移到b print format a,c 將a上最底部的圓盤移到c hanoi n 1,b,a,c 將n 1個圓盤從b經過a移到c hanoi 3,a ...