我正在研究一个河内塔的变体问题,您只能移到相邻的桩子上,而我们仅限于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)

最佳答案

使用装饰器!

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

关于python - 计算递归调用-汉诺塔,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19282445/

10-10 10:36