汉诺塔python用递归实现_python请用递归算法编程解决汉诺塔问题 在线等

展开全部

这是2113Python3系统自带的一个例子,估计5261就是4102这个意思,本来他是6个盘子,按照你要求改成4个了。递1653归算法没问题,描述也非常详细 ;)#!/usr/bin/env python3

from turtle import *

class Disc(Turtle):

def __init__(self, n):

Turtle.__init__(self, shape="square", visible=False)

self.pu()

self.shapesize(1.5, n*1.5, 2) # square-->rectangle

self.fillcolor(n/6., 0, 1-n/6.)

self.st()

class Tower(list):

"Hanoi tower, a subclass of built-in type list"

def __init__(self, x):

"create an empty tower. x is x-position of peg"

self.x = x

def push(self, d):

d.setx(self.x)

d.sety(-150+34*len(self))

self.append(d)

def pop(self):

d = list.pop(self)

d.sety(150)

return d

def hanoi(n, from_, with_, to_):

if n > 0:

hanoi(n-1, from_, to_, with_)

to_.push(from_.pop())

hanoi(n-1, with_, from_, to_)

def play():

onkey(None,"space")

clear()

try:

hanoi(6, t1, t2, t3)

write("press STOP button to exit",

align="center", font=("Courier", 16, "bold"))

except Terminator:

pass # turtledemo user pressed STOP

def main():

global t1, t2, t3

ht(); penup(); goto(0, -225) # writer turtle

t1 = Tower(-250)

t2 = Tower(0)

t3 = Tower(250)

# make tower of 6 discs

for i in range(4,0,-1):

t1.push(Disc(i))

# prepare spartanic user interface ;-)

write("press spacebar to start game",

align="center", font=("Courier", 16, "bold"))

onkey(play, "space")

listen()

return "EVENTLOOP"

if __name__=="__main__":

msg = main()

print(msg)

mainloop()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值