python - Python中的元组树结构深度

标签 python

我想做一个递归函数,用来测量a的深度 Python 2 中的元组树结构。这是麻省理工学院 AI 类(class)中的练习,我不参加该类(class)。

我从左边开始,向树的叶子添加一个零。如果不是一片叶子,我就顺着树往下走,直到找到一片叶子。我最大化 child 并将结果返回给 parent 。递归会给我最终结果。

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

#expected output
print(depth(ls4)) #expected output 4
print(depth(ls2)) #expected output 2
print(depth(ls1)) #expected output 1

#function definition
def depth(expr):
    a = []
    for j in range(len(expr)):
        if isinstance(expr,(list,tuple)) == 0:
            a.append(0)
            if len(a) == len(expr):
                return max(a)
        else:
            a.append(1 + depth(expr[j]))

最佳答案

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

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]

关于python - Python中的元组树结构深度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48503385/

相关文章:

python - 如何在python中设置时间戳

python - Dask.dataframe 或替代方案 : Scalable way of dropping rows of low frequency items

python - 自定义 account.move 上的语法错误 'date' 字段 - Odoo v8

python - 如何自定义排序 Pandas 多索引?

c++ - python 找不到用 swig 编译的模块

python - 让 Travis-CI 运行 *both* Python 2 和 3

python - Pandas 使用 pivot_table 实现带有叠加条和条组的条形图

python - 将 pandas DataFrame 转换为列表列表

python:array([...]) 是什么意思?

Python,从矩阵到数组