Skip to main content
7 of 15
added 7 characters in body
FlipTack
  • 14.7k
  • 3
  • 56
  • 102

Python 2, 290 286 272 268 bytes

This is a full program which uses a basic implementation of the shunting yard algorithm. Input is given as a quoted string, and the result is printed to STDOUT. Golfing in progress.

import re p=lambda x:'+-*/'.find(x)/2 O=[];B=[] for t in re.findall('\d+|.',input()): if'/'<t:B+=`int(t)`, elif')'<t: while O and"("<O[-1]and p(t)<=p(O[-1]):B+=O.pop() O+=t, O+=t*(')'>t) if')'==t:i=O[::-1].index('(');B+=O[-i:];O=O[:~i] print' '.join(B+O[::-1]) 

###Try it online!

Some interesting features of this answer:

  • p=lambda x:'+-*/'.find(x)/2 is a function to get the precedence of an operator. It gets the operator's location in the string +-*/ floor-divided by 2. This results in 1 for addition and subtraction, but 2 for multiplication and division.
  • re.findall('\d+|.',input()) this uses regex to tokenize the input - matching any group of consecutive digits as one token, and any other character as a 1-byte operator token. Although this also parses whitespace as tokens, they have no effect in the main loop.
  • Later on, to check whether a token is an integer, we do '/'<t. As all other math symbols in this challenge have ASCII code-points below '/', this will only evaluate to True for integers.
FlipTack
  • 14.7k
  • 3
  • 56
  • 102