An expression analysis algorithm in python?

I have the following 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 )

It's hard for me to figure this out, since I don't find Python docs very useful for this situation. Can someone tell me which line: for operator in ["+-", "*/"]: means? I know its structure as for every string variable, which is an operator in an array of these two elements, but why is it written like this ["+ -, * /"]? How does Python separate this? At the first iteration, the "+ -" operator?

Any help would mean a lot. Thanks

+4
source share
1 answer

You're right; for operator in ["+-", "*/"]: means that the operator will be "+-" first time through and "*/" second time through the loop.

Notice how later he checks to see if there is strinput[p] in operator . Python treats the string as a list of characters, so this expression will only be true if strinput[p] is "+" or "-" for the first time and "*" or "/" for the second time.

(The reason they do this is because the order of the "+" and "-" operations "-" to get an equal but lower priority of "*" and "/" )

+4
source

Source: https://habr.com/ru/post/1483993/


All Articles