Python 河内之塔非递归:我的代码正确吗?
我已经使用非递归方法为河内塔问题编写了以下代码。我猜这是不正确的,因为移动的次数不是2**n-1,例如,要移动3个磁盘,它必须生成7个移动。提前谢谢Python 河内之塔非递归:我的代码正确吗?,python,python-3.x,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
######################
# 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()
我认为您的算法存在根本性缺陷(没有冒犯): 按照我的阅读方式,从“左”堆栈中取出num-1个“环”,将它们放在“中”堆栈上,然后将剩余的环从“左”堆栈移动到“右”堆栈(目标堆栈)。我以为河内塔楼的运作方式是一次移动一圈 因此,在您的情况下,当Num=3时,1次移动后Aux=2,这应该是不可能的 也许你可以看看这里:
它以多种不同的形式描述了河内塔问题 您是否尝试将此与现有算法匹配?在将此与算法匹配时,我发现了一些问题。我将编辑我的问题。我不知道您的“算法”在哪里。目前,您基本上要求用户移动,然后再进行移动。到目前为止,您既没有检查移动的有效性(在这个问题中并非每个移动都有效),也没有生成移动的算法。我错过了什么吗?@Jakob S:谢谢你指出这一点,我想知道我错过了什么。我并没有检查移动的有效性,尽管我发现我并没有考虑磁盘大小。我知道它确实有缺陷,这就是我想知道我到底出了什么问题。事实上,我想知道如何获得合法的移动检查。ThanksI相信递归解将为河内塔生成正确的解。我会自己做的。谢谢
Aux = Num-1
Src = Src-Aux
Dst = Src