python - 汉诺塔非递归: Is my code correct?

标签 python python-3.x

我使用非递归方法为汉诺塔问题编写了以下代码。我猜这是不正确的,因为移动次数不是 2**n - 1,例如,要移动 3 个磁盘,它必须生成 7 次移动。提前致谢。

######################
#   Towers of Hanoi  #
######################

numbers = []

def TowersofHanoi():
# Proram to simulate Towers of hanoi
# Objective is to move the disks from A to C 
# with B as a temporary varialbel


    print "Program to simulate Towers of Hanoi"
    print "Users will input numbers of disks, which is 'A'"
    print "The disks have to be moved from A to C"
    print "With B as temporary placeholder"


    print "Enter the number of disks to be moved:",

    Num = int (raw_input("> "))
    Src = Num
    Aux = 0
    Dst = 0
    print "you have entered %d disks to be moved"
    print "Source is -->", Src
    print "Auxillary is -->", Aux
    print "Destination is -->", Dst


    print "Disk positions after the placement:"

    #B = A-1
    #print B
    while Num >= 1: 
        print Num
        Aux = Num-1
        Src = Src-Aux   
        Dst = Src   

        print "Source is -->", Src
        print "Auxillary is -->", Aux
        print "Destination is -->", Dst
        Src = Aux
        Num = Num-1

        numbers.append(Dst)
    print numbers


    print "The task of accomplishing the movements of disk is over"
    print "This completes TOWERS OF HANOI!"
    print "Final disk positions are:"
    print "Source is -->", Src
    print "Auxillary is -->", Aux
    print "Destination is -->", len(numbers)

TowersofHanoi()

最佳答案

我认为您的算法存在根本性缺陷(无罪):

Aux = Num-1
Src = Src-Aux   
Dst = Src  

按照我的阅读方式,您从“左”堆栈中取出 num-1 个“环”并将它们放在“中间”堆栈中,然后将剩余的环从“左”堆栈移至“右”堆栈(目标堆栈)。我以为汉诺塔的工作方式是一次移动 1 个环?

因此,在您的情况下,当 Num = 3 时,Aux = 2 后 1 步,这是不可能的。

也许在这里看看:http://en.wikipedia.org/wiki/Tower_of_Hanoi#Iterative_solution 它以多种不同的形式描述了汉诺塔问题。

关于python - 汉诺塔非递归: Is my code correct?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11825463/

相关文章:

python - 属性错误 : module 'pkg_resources' has no attribute 'safe_name' oauthlib install

Python 2 与 Python 3 字符串 pickle

python - 匹配一个单词,后跟任意顺序的两个可选组

python - 如果有条件,模块对象在 sleep 状态下不可调用(python)

python - "decision matrix"的干净实现

python - 检查 git 上的 Python 包是否比本地更新

python - 无法使用 pip 在 MacOSX 上安装模拟包

python 3.4 多处理

python - 如果插入时间在时间​​范围内则插入表

python - 将复杂模块导入到Processing.py中