我不打算为您调试代码,但我将尝试回答您遇到的具体问题:but I can't wrap my head around the recursive thinking necessary to
have it trace all the paths and put them neatly in a list:
要使递归函数将其结果收集到列表中,需要执行以下操作:def _myfn(data, res):
if (..recurse..):
return _myfn(data2, res + [item]) # item being the result of this iteration
else:
# terminal case
return res
def myfn(data):
return _myfn(data, [])
您可以将这些压缩为一个函数:
^{pr2}$
或者您可以使_myfn成为myfn的本地:def myfn(data):
def _myfn(data, res):
if (..recurse..):
return _myfn(data2, res + [item])
else:
# terminal case
return res
return _myfn(data, [])
当涉及到递归思维时,只需记住(1)始终处理基本情况;-)和(2)在每次递归中首先(i)生成所有可能的下一步步骤,(ii)然后在每个递归中递归。为(i)编写一个单独的函数通常会清除一些代码。在
作为一个递归函数的例子,该函数在二叉树中查找从根到叶的所有路径(稍微按教学法编码)--这就是您要做的:# tree = (root, left, right)
def all_paths(t):
leaf_paths = []
def _all_paths(t, res):
root, left, right = t
# calculate all next-steps
next_steps = [step for step in [left, right] if step]
if not next_steps:
# handle base case (found one solution)
leaf_paths.append(res + [root])
else:
# recurse
for step in next_steps:
_all_paths(step, res + [root])
_all_paths(t, [])
return leaf_paths
>>> all_paths( (2, (), ()) )
[[2]]
>>> all_paths(
... (2,
... (3, (), ()),
... (4, (), ())))
[[2, 3], [2, 4]]
这张图呢
>>> t = (
2,
(7,
(2, (), ()),
(6,
(5, (), ()),
(11, (), ()))),
(5,
(),
(9,
(4, (), ()),
())))
>>> print all_paths(t)
[[2, 7, 2], [2, 7, 6, 5], [2, 7, 6, 11], [2, 5, 9, 4]]