HI I have a function parse()
that takes a list of operators and operands (ex ['+', '20', '10']
) tokens, and an index i, and constructs a tree from them. When an operator ( a node with a .left
and .right
) is found, the function goes down until it reaches a literal ( a number ) or a letter variable. The problem is I would like the index i that is changing within the recursion to stay modified when the recursion on the left side is done and the function moves on to the right side. For example, to get this tree from [-, //, y, 2, x]:
I have written this:
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])
When the SubtractNode is made, i is 0 and then increments normally, but when the left side is done i is again 0 and the parse(tokens, i + 2)
points to the y instead of the x, making something like this:
How is it possible to make the above tree without using pop()
in tokens?
i
be 0 whenmkSubtractNode
is called? What would be value intokens
? – thefourtheye 15 hours ago