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)")
If you don't mind a regex-heavy approach, here's a single-method version in Ruby that handles precedence correctly and maintains the ability to pass in operators:
def in_to_pre_fix(expr, opers=%w(*/ +-))
subex = "\\s*(?:(?:<([^>]+)>)|([\\w]+))\\s*"
while expr !~ /^<[^>]*>$/ and expr.sub!(/(?:^|\()([^)(]*)(?:\)|$)/) { | m |
opers.each { | oper |
while m.sub!(Regexp.new("#{subex}([#{Regexp.quote(oper)}])#{subex}"),
'<\3 \1\2 \4\5>'); end }
m.tr_s("() "," ").strip() }; end
expr.delete("<>")
end
(I'm new to Ruby, so it may not be idiomatic or preferred whitespace-style.)