1

我正在研究一个处理河内塔问题的变体的问题,您只能移动到相邻的钉子,而我们仅限于 3 个钉子问题。我已经获得了打印出光盘数量所需移动的代码,但我无法弄清楚如何打印递归调用的数量。

def adjacent_hanoi(num_discs, start_peg, end_peg):
"""
Given the number of discs in Adjacent-Peg Tower of Hanoi:
1. Prints each move necessary to solve the puzzle (minimum number of moves)
2. Returns the total number of moves required

For this problem, discs should always start on the first peg and
end on the last peg.

num_discs: an integer number of discs
start_peg: starting peg
end_peg: ending peg
returns: an integer number of moves
"""

if num_discs > 0:
    adjacent_hanoi(num_discs-1, start_peg, end_peg)
    print "Move disc", num_discs, "from peg", start_peg, "to peg", 2
    adjacent_hanoi(num_discs-1, end_peg, start_peg)
    print "Move disc", num_discs, "from peg", 2 , "to peg", end_peg
    adjacent_hanoi(num_discs-1, start_peg, end_peg)
4

5 回答 5

2

使用装饰器!

class Counter(object):
    def __init__(self, func):
        self.func = func
        self.count = 0
    def __call__(self, *args):
        self.count += 1
        return self.func(*args)
@Counter
def your_function():
    return "Hello"

for i in range(10):
     print your_function()

print your_function.count #=> 10
于 2013-10-09T21:28:38.840 回答
0

添加一个作为全局变量的计数器。在函数开始时将其增加 1。

recursionCounter = 0

def functionToTrack:
    recursionCounter += 1
    #the rest of your code...

如果您只想跟踪递归级别,recursionCounter 请在每次从函数外部调用时将其存储并重置为 0。

functionToTrack()
firstCallRecursion = recursionCounter
recursionCounter = 0
functionToTrack()
secondCallRecursion = recursionCounter
recursionCounter = 0
于 2013-10-09T20:56:13.067 回答
0

您可以添加一个新参数,让我们调用它count

def adjacent_hanoi(num_discs, start_peg, end_peg, count):

您可以在每次递归调用时增加它。

另一种方法是添加一个全局变量并增加它。如果没什么特别的,我会这样做。

于 2013-10-09T21:00:59.213 回答
0

我建议在您的函数中添加一个附加参数作为增量计数器:

def adjacent_hanoi(num_discs, start_peg, end_peg, count=0):
    #do something with num_discs, start_peg, and end_peg
    count += 1
    print count
    return adjacent_hanoi(num_discs, start_peg, end_peg, count)
于 2013-10-09T21:02:00.770 回答
0

这是一个数学序列。

只需制作一个辅助方法

hanoi_recurse(num_discs, start, end)

它与第一种方法做同样的事情

现在你的代码看起来像

def adjacent_hanoi(num_discs, start_peg, end_peg):
    adjacent_hanoi_recurse(num_discs, start_peg, end_peg)
    print (3 ** num_discs) - 1
于 2013-10-11T00:55:54.847 回答