python - 计算结构有多深的最简单方法?

标签 python data-structures abstract-syntax-tree

假设我有一个像这样的 AST 结构(列表列表):

 [+, [*, a,b],[*,c,d] ]
 [+, [*, a,b],[*,c,[ +, d, e] ] ]

计算结构深度(即有多少层)的最简单和/或最快方法是什么?

作为第二个选项,您也可以将其作为字符串使用,而不是列表列表 (LoL)。例如:

"[+, [*, a,b],[*,c,d] ]"

我可以同时使用两者。

最佳答案

您可以保留方括号的数量。 您可以找到更详细的解释here 。 以下是代码的改编:

string = str(tree)

currentDepth = 0
maxDepth = 0
for c in string:
    if c == '[':
        currentDepth += 1
    elif c == ']':
        currentDepth -= 1

    maxDepth = max(maxDepth, currentDepth)

同样的警告,如果您的数据可能包含 '['']',这将会中断。 在这种情况下,您需要为这些方括号定义转义方法。

关于python - 计算结构有多深的最简单方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46043126/

相关文章:

python - 如何在 tkinter 的主窗口前面放置一个顶层窗口?

algorithm - 如何证明 n 个节点的二叉堆中有 ceil(n/2) 个叶子节点?

c++ - 使用C++标准库以对数时间进行堆化

Python AST 到字典结构

python - 在 numpy 数组中查找子数组的索引

python - Yellowbrick:增加 Yellowbrick 生成的图表上的字体大小

algorithm - 插入缩写词

typescript 编译器 : how to get FunctionDeclaration of the original function from CallExpression?

c++ - 如何解析 C++ 以创建 AST?

python - 类型错误 : ufunc 'subtract' did not contain a loop with signature matching types dtype ('<U8' ) dtype ('<U8' ) dtype ('<U8' )