python - 递归解析而不是使用 pop

标签 python recursion

我将如何递归地解析 token ,而不是使用 pop?

def parse(tokens, i = 0):
    """parse: tuple(String) * int -> (Node, int)
    From an infix stream of tokens, and the current index into the
    token stream, construct and return the tree, as a collection of Nodes, 
    that represent the expression.

    NOTE:  YOU ARE NOT ALLOWED TO MUTATE 'tokens' (e.g. pop())!!!  YOU
        MUST USE 'i' TO GET THE CURRENT TOKEN OUT OF 'tokens'
    """
    i = 0
    if tokens.pop(0) == '+':
        return mkAddNode(parse(tokens), parse(tokens))
    elif tokens.pop(0) == '-':
        return mkSubtractNode(parse(tokens), parse(tokens))
    ....

我正在努力将其转换为使用递归调用,而不是在函数中使用 tokens.pop()

最佳答案

递归调用parse时递增i:

def parse(tokens, i=0):
    """parse: tuple(String) * int -> (Node, int)
    From an infix stream of tokens, and the current index into the
    token stream, construct and return the tree, as a collection of Nodes, 
    that represent the expression.

    NOTE:  YOU ARE NOT ALLOWED TO MUTATE 'tokens' (e.g. pop())!!!  YOU
        MUST USE 'i' TO GET THE CURRENT TOKEN OUT OF 'tokens'
    """
    if tokens[i] == '+':
        return mkAddNode(parse(tokens, i+1), parse(tokens, i+1))
    elif tokens[i] == '-':
        return mkSubtractNode(parse(tokens, i+1), parse(tokens, i+1))

关于python - 递归解析而不是使用 pop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20051552/

相关文章:

Haskell 理解 fmap

java - 这段代码中输入值没有增加,函数用 0 值调用自身?

python - 在虚拟环境中安装 pysvn

Python:将二维数组的特定行选择到新数组中的优雅方法是什么?

python - 如何在AWS EC2上安装Chromadb?

python - 我想提取类对象拥有的所有值

c# - 升序排列

python - 简单的递归函数

python - 哪些 python 模块可用于协助标准库中的守护进程?

python - ScikitLearn 随机森林中的欠采样与 class_weight