Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Another python, but recursive:

  def doit(expr):
    expr=''.join(expr.split())
    if expr.startswith('('):
        (left,size) = doit(expr[1:])
        size+=2
    else:
        left = re.compile('(\w+)').match(expr).groups(0)[0]
        size = len(left)
    rest = expr[size:]
    if rest=='' or rest[0]==')':
        return left,size
    op = re.compile('([*/+-])').match(rest).groups(0)[0]
    right,size2 = doit(rest[1:])
    return '(%s %s %s)'%(op, left, right) ,size+size2+1


It doesn't work correctly. Example:

    print parse_expr("1+2/3/4-5*6")
Result:

    (+ 1 (/ 2 (/ 3 (- 4 (* 5 6)))))


Yeah, it doesn't take into account operator precedence :(




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: