递归解析此树结构的所有级别的最佳方法是什么。首先是三个级别,但是应该如何解析其余数据呢?这是我无法完成的一次Codility测试。这个问题还有更多,但这就是我遇到的问题。
tree = (5, (8, (12, None, None), (2, None, None)),(9, (7, (1, None, None), None), (4, (3, None, None), None)))
def recurse(T):
calc = 0
def do_calc(T, calc):
if T == ():
return calc
calc += 1
return do_calc(T[1:], calc)
return do_calc(T, calc)
print recurse(tree)
看来您想获取树的深度。这是递归的典型解决方案:
tree = (5, (8, (12, None, None), (2, None, None)),(9, (7, (1, None, None), None), (4, (3, None, None), None)))
def tree_depth(node):
if not isinstance(node, tuple):
return 1
else:
return max(tree_depth(subnode) for subnode in node) + 1
print tree_depth(tree)
输出为5。
示例代码中使用了内置函数max和generator表达式。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句