gpt4 book ai didi

python - 计算递归调用 - 汉诺塔

转载 作者:行者123 更新时间:2023-12-01 05:35:07 26 4
gpt4 key购买 nike

我正在研究一个处理汉诺塔问题的变体的问题,在该问题中,您只能移动到相邻的钉子,而我们仅限于 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com