Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 递归求解河内塔_Python - Fatal编程技术网

Python 递归求解河内塔

Python 递归求解河内塔,python,Python,我知道河内塔背后的想法,也知道算法,但我在实现它时遇到了困难 class Hanoi: def __init__(self, n): == code== def move(self, src, dst): =code for moving the disk from source to destination== def spare(self, src, dst): ==Returns the peg which is not src an

我知道河内塔背后的想法,也知道算法,但我在实现它时遇到了困难

class Hanoi:
    def __init__(self, n):
       == code==

    def move(self, src, dst):
   =code for moving the disk from source to destination==

    def spare(self, src, dst):
    ==Returns the peg which is not src and dst==

    def print_pegs(self):


h = Hanoi(4)

def hanoi(n, src, dst):         
        if n==1:
           h.move(src,dst)
        else:
            spare=h.spare(src,dst)
            hanoi(n-1,src,spare)
            hanoi(1,src,dst)
            hanoi(n-1,spare,dst)

hanoi(4, 0, 2)

我遇到的问题是,我不知道如何将递归定义与类函数结合起来移动磁盘。

您需要将递归调用放入
move()
spare()
的主体中,并将函数
hanoi()
的逻辑移动到相关方法中

所以


您需要将递归调用放入
move()
spare()
的主体中,并将函数
hanoi()
的逻辑移动到相关方法中

所以


这是一个语法问题吗?我不确定我是否遵循.def hanoi是一种递归语法,但我需要将它添加到h.move(src,spare)等的某个地方,但我遇到了如何执行的问题这里有一个解决问题的方法。“不知道如何将递归定义与类功能结合起来”和“我想让类保持原样并将递归放在hanoi函数中”是矛盾的。你想要什么?这是一个语法问题吗?我不确定我是否遵循。def hanoi是一个递归的语法,但我需要将它添加到h.move(src,spare)等的某个地方,但我在如何做这件事上遇到了麻烦。这是一个解决问题的方法。”不知道如何将递归定义与类函数结合起来”和“我想让类保持原样,并将递归放在hanoi函数中“它们相互矛盾。你想要什么?有没有办法在hanoi函数中实现它,我想让类保持原样,将递归放在hanoi函数中你不需要创建类,直接编写函数即可。你使用的是Java示例教材吗?有没有办法在hanoi函数中实现它,我想让类保持原样,将递归放在hanoi函数中你不需要创建类,直接编写函数即可。你使用的是带有Java示例的教科书吗?
class Hanoi(object):

    # snip

    def move(self, src, dst):

        # your logic goes here
        # example of a recursive call
        self.move(foo, bar)