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/zh-hant/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

發表回復

登錄後才能評論