Pregunta

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

¿Fue útil?

Solución

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 "/")

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top