我正在处理一个问题,处理河内塔问题的变化问题,你只能移动到相邻的钉子,我们只能解决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)
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分:0)
您可以添加新参数,我们可以将其称为count
。
def adjacent_hanoi(num_discs, start_peg, end_peg, count):
您可以在每次递归调用时递增它。
另一种方法是添加一个全局变量并将其递增。如果它没什么特别的话,我会这样做。
答案 3 :(得分: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)
答案 4 :(得分: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