嗨,我有一个函数parse(),它接收一个运算符和操作数(例如[[”,’20’,’10’])标记的列表以及一个索引i,并从中构造一个树.当找到一个运算符(带有.left和.right的节点)时,该函数将关闭,直到到达文字(数字)或字母变量.问题是当左侧的递归完成并且函数移至右侧时,我希望递归内变化的索引i保持修改状态.例如,要从[-,//,y,2,x]中获得这棵树:
我写了这个:
def parse(tokens, i):
"""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."""
if tokens[i].isdigit():
return mkLiteralNode(tokens[i])
elif tokens[i] == "+":
return mkAddNode(parse( tokens, i + 1 ), parse( tokens, i + 2 )) # first argument is the node.left, second is the node.right
elif tokens[i] == "-":
return mkSubtractNode(parse( tokens, i + 1 ), parse( tokens, i + 2 ))
elif tokens[i] == "*":
return mkMultiplyNode(parse( tokens, i + 1 ), parse( tokens, i + 2 ))
elif tokens[i] == "//":
return mkDivideNode(parse( tokens, i + 1 ), parse( tokens, i + 2 ))
else:
return mkVariableNode(tokens[i])
当创建SubtractNode时,i为0,然后正常递增,但是当完成左侧时,i再次为0,parse(tokens,i 2)指向y而不是x,进行如下操作:
在令牌中不使用pop()的情况下如何制作上述树?