Python中元组树结构的深度

时间:2018-01-29 14:20:08

标签: python

我想制作一个递归函数,用于测量a的深度 Python中的元组树结构。这是麻省理工学院人工智能课程中的练习,我没有参加课程。

我从左边开始,在树的叶子上加零。如果不是叶子,我会一直走到树下,直到我到达一片叶子。我对孩子们进行了最大化并将结果返回给父母。递归会给我最终的结果。

<body>
<script src="/files/mycss.css"></script>
<script src="/files/index.js"></script>
<script src="/files/service-worker.js"></script>
</body>

2 个答案:

答案 0 :(得分:3)

在递归函数中,使用计数器跟踪当前深度:

ls0 = 'x'
ls1 = ('expt', 'x', 2)
ls2 = ('+', ('expt', 'x', 2), ('expt', 'y', 2))
ls4 = ('/', ('expt', 'x', 5), ('expt', ('-', ('expt', 'x', 2),1), ('/', 5, 2)))
tree = [ls1, ls2, ls4]
def depth(b, count=0):
   if isinstance(b, str) or isinstance(b, int) or all(not isinstance(i, tuple) for i in b):
     yield count+1
   else:
     for i in b:
       for c in depth(i, count+1):
         yield c

final_results = [max(i) for i in list(map(list, list(map(depth, tree))))]

输出:

[1, 2, 4]

答案 1 :(得分:0)

您也可以尝试这种简单的递归解决方案:

def depth(l):
    depths = [depth(item) for item in l if isinstance(item, tuple)]

    if len(depths) > 0:
        return 1 + max(depths)

    return 1

ls0 = ('x')
ls1 = ()
ls2 = ('expt', 'x', 2)
ls3 = ('+', ('expt', 'x', 2), ('expt', 'y', 2))
ls4 = ('/', ('expt', 'x', 5), ('expt', ('-', ('expt', 'x', 2),1), ('/', 5, 2)))

tuples = [ls0, ls1, ls2, ls3, ls4]
for tup in tuples:
    print(depth(tup))

哪个输出:

1
1
1
2
4
相关问题