python实现汉诺塔程序的简单介绍

本文目录一览:

python利用递归解决汉诺塔问题,求大神解释一下代码

这是一个典型的递归程序

当只有一层的时候,直接把x放到z上结束

当大于1层的时候,先把x和z放到y上,然后继续递归

把y放到x上,然后放到z上,结束处理

python解决汉诺塔问题?

解汉诺塔最简单的做法就是递归:

类似如何将大象装进冰箱:1)将冰箱门打开;2)把大大象放进去;3)把冰箱门关上……

我们将所有的盘都在同一个杆上从大到小排列视为【完美状态】,那么,目标就是将最大盘片为n的完美状态从a杆移到b杆,套用装大象的思路,这个问题同样是三步:

1)把n-1的完美状态移到另一个杆上;

2)把n移到目标杆上;

3)把n-1的完美状态移到目标杆上。

如下:

标题:用Python编码描述汉诺塔步骤

#-*- coding:utf-8 -*-

count = 0

def hano():

    

    def hanoi(n,x,y,z):

        global count

        count += 1

        if n == 1:

            print(‘Monving %d’ % n, ‘from ‘,x,’to’,z)

        else:

            hanoi(n-1,x,z,y)

            print(‘Monving %d’ % n,  ‘from ‘,x,’to’,z)

            hanoi(n-1,y,x,z)

    return hanoi

n = int(input(“请输入汉诺塔的层数 :”))

hano()(n,’source’,’helper’,’target’)

print(“The total number of steps required is: “,str(count))

———–分-割-线-是-我—————-

复制分割线以上的代码,保存为hannoi.py,在python 3 下运行,得到结果如题所示。

【python】汉诺塔递归

系统自带的演示代码,可以研究一下

#!/usr/bin/env python3

“””       turtle-example-suite:

         tdemo_minimal_hanoi.py

A minimal ‘Towers of Hanoi’ animation:

A tower of 6 discs is transferred from the

left to the right peg.

An imho quite elegant and concise

implementation using a tower class, which

is derived from the built-in type list.

Discs are turtles with shape “square”, but

stretched to rectangles by shapesize()

 —————————————

       To exit press STOP button

 —————————————

“””

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(6,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()

Python 中关于汉诺塔的问题,这个程序,给定参数n的数值,怎么在程序里运行

有a,b,c 三个柱子,有n个从大到小的盘子,大盘子必须一直放在小盘子的下面,借助柱子b将n个盘子从a移到c

这个问题可以分解成下面的子题

先借助柱子c,将n-1个盘子从a移到b: hanoi(n-1,a,c,b)

将第n个盘子从a移到c :print(a,’–‘,c)

然后借柱子 a将已经移致b上的n-1个盘子移到c上:hanoi(n-1,b,a,c)

这样就移好了,将原问题分解成规模更小同样的子问题,递归解决,

求python大神帮忙解释一下 这个汉诺塔程序的步骤

def my_print(args):

print args

def move(n, a, b, c):

my_print ((a, ‘–‘, c)) if n==1 else (move(n-1,a,c,b) or move(1,a,b,c) or move(n-1,b,a,c))

注释:汉诺塔模型输入move (n, ‘a’, ‘b’, ‘c’)

例如n=3

move(2,a,c,b)自循环

move(1,a,b,c)

move(2,b,a,c) 自循环

循环完毕,输出

你这段代码也是类似自循环

原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/247565.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
小蓝小蓝
上一篇 2024-12-12 13:21
下一篇 2024-12-12 13:21

相关推荐

  • Python周杰伦代码用法介绍

    本文将从多个方面对Python周杰伦代码进行详细的阐述。 一、代码介绍 from urllib.request import urlopen from bs4 import Bea…

    编程 2025-04-29
  • Python计算阳历日期对应周几

    本文介绍如何通过Python计算任意阳历日期对应周几。 一、获取日期 获取日期可以通过Python内置的模块datetime实现,示例代码如下: from datetime imp…

    编程 2025-04-29
  • 如何查看Anaconda中Python路径

    对Anaconda中Python路径即conda环境的查看进行详细的阐述。 一、使用命令行查看 1、在Windows系统中,可以使用命令提示符(cmd)或者Anaconda Pro…

    编程 2025-04-29
  • Python中引入上一级目录中函数

    Python中经常需要调用其他文件夹中的模块或函数,其中一个常见的操作是引入上一级目录中的函数。在此,我们将从多个角度详细解释如何在Python中引入上一级目录的函数。 一、加入环…

    编程 2025-04-29
  • Python列表中负数的个数

    Python列表是一个有序的集合,可以存储多个不同类型的元素。而负数是指小于0的整数。在Python列表中,我们想要找到负数的个数,可以通过以下几个方面进行实现。 一、使用循环遍历…

    编程 2025-04-29
  • 蝴蝶优化算法Python版

    蝴蝶优化算法是一种基于仿生学的优化算法,模仿自然界中的蝴蝶进行搜索。它可以应用于多个领域的优化问题,包括数学优化、工程问题、机器学习等。本文将从多个方面对蝴蝶优化算法Python版…

    编程 2025-04-29
  • Python清华镜像下载

    Python清华镜像是一个高质量的Python开发资源镜像站,提供了Python及其相关的开发工具、框架和文档的下载服务。本文将从以下几个方面对Python清华镜像下载进行详细的阐…

    编程 2025-04-29
  • Python字典去重复工具

    使用Python语言编写字典去重复工具,可帮助用户快速去重复。 一、字典去重复工具的需求 在使用Python编写程序时,我们经常需要处理数据文件,其中包含了大量的重复数据。为了方便…

    编程 2025-04-29
  • Python程序需要编译才能执行

    Python 被广泛应用于数据分析、人工智能、科学计算等领域,它的灵活性和简单易学的性质使得越来越多的人喜欢使用 Python 进行编程。然而,在 Python 中程序执行的方式不…

    编程 2025-04-29
  • python强行终止程序快捷键

    本文将从多个方面对python强行终止程序快捷键进行详细阐述,并提供相应代码示例。 一、Ctrl+C快捷键 Ctrl+C快捷键是在终端中经常用来强行终止运行的程序。当你在终端中运行…

    编程 2025-04-29

发表回复

登录后才能评论