递归解析而不是使用pop

时间:2013-11-18 15:31:32

标签: python recursion

我如何递归地解析令牌,而不是使用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()

2 个答案:

答案 0 :(得分:1)

递归调用i后递增parse

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))

答案 1 :(得分:0)

而不是实际弹出,只需查看第一个元素,并在递归调用时,确保剥离第一个字符:

# just doing the split once
first, remaining = tokens[0], tokens[1:]

if first == '+':
    return mkAddNode(parse(remaining), parse(remaining))
elif first == '-':
    return mkSubtractNode(parse(remaining), parse(remaining))

或者我刚才看到你应该使用索引i,你也可以在每次递归调用时移动指针;当然,您不希望每次在解析函数中将i重置为零:

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))

无论如何,您还应该处理令牌流结束的情况。对于基于索引的方式,这将是i > len(tokens)