pythonを勉強中、再帰法の題材にでてくる、ハノイの塔 のプログラムがどうしても理解できません。
演習問題で、「ハノイの塔をタートルで動かせ」とありましたのでなんとか動かしてみました。
コードを入力
import turtle
wn = turtle.Screen()
t1 = turtle.Turtle()
t1.resizemode("user")
t1.shapesize(1,1,1)
t1.shape("circle")
t1.color("red")
t1.speed(3)
t1.up()
t1.setpos(0,180)
t2 = turtle.Turtle()
t2.resizemode("user")
t2.shapesize(1,2,1)
t2.shape("circle")
t2.color("green")
t2.speed(3)
t2.up()
t2.setpos(0,150)
t3 = turtle.Turtle()
t3.resizemode("user")
t3.shapesize(1,3,1)
t3.shape("circle")
t3.color("brown")
t3.speed(3)
t3.up()
t3.setpos(0,120)
t4 = turtle.Turtle()
t4.resizemode("user")
t4.shapesize(1,4,1)
t4.shape("circle")
t4.color("black")
t4.speed(3)
t4.up()
t4.setpos(0,90)
t5 = turtle.Turtle()
t5.resizemode("user")
t5.shapesize(1,5,1)
t5.shape("circle")
t5.color("yellow")
t5.speed(3)
t5.up()
t5.setpos(0,60)
t6 = turtle.Turtle()
t6.resizemode("user")
t6.shapesize(1,6,1)
t6.shape("circle")
t6.color("pink")
t6.speed(3)
t6.up()
t6.setpos(0,30)
t7 = turtle.Turtle()
t7.resizemode("user")
t7.shapesize(1,7,1)
t7.shape("circle")
t7.color("cyan")
t7.speed(3)
t7.up()
t7.setpos(0,0)
t8 = turtle.Turtle()
t8.resizemode("user")
t8.shapesize(1,8,1)
t8.shape("circle")
t8.color("violet")
t8.speed(3)
t8.up()
t8.setpos(0,-30)
def move_turtle(t_num,to_pole):
if t_num ==1 :
t_num = t1
if t_num ==2 :
t_num = t2
if t_num ==3 :
t_num = t3
if t_num ==4 :
t_num = t4
if t_num ==5 :
t_num = t5
if t_num ==6 :
t_num = t6
if t_num ==7 :
t_num = t7
if t_num ==8 :
t_num = t8
count_a = 0
count_b = 0
count_c = 0
for t in (t1,t2,t3,t4,t5,t6,t7,t8):
if t.xcor() == 0:
count_a = count_a + 1
if t.xcor() == 150:
count_b = count_b + 1
if t.xcor() == 300:
count_c = count_c + 1
to_a_y = count_a * 30 - 30
to_b_y = count_b * 30 - 30
to_c_y = count_c * 30 - 30
if to_pole =="A":
t_num.sety(200)
t_num.setx( 0)
t_num.setpos(0 ,to_a_y)
if to_pole =="B":
t_num.sety(200)
t_num.setx(150)
t_num.setpos(150 ,to_b_y)
if to_pole =="C":
t_num.sety(200)
t_num.setx(300)
t_num.setpos(300 ,to_c_y)
def moveTower(height,fromPole, toPole, withPole):
if height >= 1:
moveTower(height-1,fromPole,withPole,toPole)
moveDisk(height,fromPole,toPole)
moveTower(height-1,withPole,toPole,fromPole)
def moveDisk(height,fp,tp):
print("moving disk",height," from",fp,"to",tp)
move_turtle(height,tp)
moveTower(8, "A", "C", "B")
wn.exitonclick()
8段まで動かしてイメージを作ってます。
じっくり眺めてても古い頭ではなかなか理解できません。