4

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

10
  • It looks like a very unpythonic algorithm to me, if I can tell. Commented Jun 2, 2013 at 1:23
  • 1
    for operator in ["+-", "*/"]: it's a loop iterating through list which has two elements "+-" and "*/" Commented Jun 2, 2013 at 1:23
  • @Elazar: What would you improve? Commented Jun 2, 2013 at 1:25
  • @Blender truth is, I don't really know. It looks too similar to something I wrote in an introduction-to-CS course. in C. Can't you improve it? For one, it takes advantage of the fact that an operator is single character (which breaks in python3). It just feels... awkward. Commented Jun 2, 2013 at 1:40
  • @Elazar: How would it break in Python 3? Commented Jun 2, 2013 at 1:43

1 Answer 1

4

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

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

(The reason they do this is for order of operations- "+" and "-" get equal but lower precedence to "*" and "/")

Sign up to request clarification or add additional context in comments.

1 Comment

Yea, thank you! :) I already got by time what it means by it and exactly got it on 6*3+2. It goes from right to left, first checking lower priority operators, because it can group by them, since higher priority operators need to be executed for first. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.