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

Solution in python that parses infix expression from string and returns a list of tokens in prefix form.

    def parse(s):
        for operator in ["+-", "*/"]:
            depth = 0
            for p in xrange(len(s) - 1, -1, -1):
                if s[p] == ')': depth += 1
                if s[p] == '(': depth -= 1
                if not depth and s[p] in operator:
                    return [s[p]] + parse(s[:p]) + parse(s[p+1:])
        s = s.strip()
        if s[0] == '(':
            return parse(s[1:-1])
        return [s]
    print parse("1+3* 4/haha-5*(2+3.14  ) * (4+5)")
Edit: grammer


Edit: grammer

I think you need one more edit. :-)




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

Search: