I have next algorithm for parsing expressions in Python:
def parse(strinput):
for operator in ["+-", "*/"]:
depth = 0
for p in range(len(strinput) - 1, -1, -1):
if strinput[p] == ')': depth += 1
elif strinput[p] == '(': depth -= 1
elif depth==0 and strinput[p] in operator:
# strinput is a compound expression
return (strinput[p], parse(strinput[:p]), parse(strinput[p+1:]))
strinput = strinput.strip()
if strinput[0] == '(':
# strinput is a parenthesized expression?
return parse(strinput[1:-1])
# strinput is an atom!
return strinput
(it can be found here: http://news.ycombinator.com/item?id=284842)
I have hard time understanding it, since I don't find Python docs very helpful for this situation. Can someone tell me what line: for operator in ["+-", "*/"]:
means?
I know it's structure like for each string variable which is operator in array of this 2 elements, but why is it written like this ["+-, */"]? How does Python separate it? In first iteration, operator is "+-"?
Any help would mean a lot. Thanks