I am writing a small calculator (with prefix notation) and I'm curious how I'd convert prefix notation to infix notation. I currently have a function, but it's being weird, and I'm not sure how to fix it. By being weird, I mean that if given ['+', x, y]
it will return (() + x + () + y)
which is confusing me. Here's the code.
def pre_in(read):
#print read
tempOp = read[0]
body = read[1:]
expr = []
for i in range(len(body)-1):
if not isinstance(body[i], list) and body[i] != " ":
expr.append(str(body[i]))
expr.append(tempOp)
else:
expr.append(str(pre_in(body[i])))
expr.append(tempOp)
try:
if not isinstance(body[-1], list):
expr.append(str(body[-1]))
else:
expr.append(str(pre_in(body[-1])))
except:
pass
if expr != None: return "("+' '.join(expr)+")"
What am I doing wrong?
Actually your code works fine.
print pre_in ( ['+', 8, 9] )
yields
(8 + 9)
EDIT: As the others have stated, maybe you want to use a stack. Here a simple sandbox implementation with some examples (it produces many parenthesis but those don't hurt):
class Calculator:
def __init__ (self):
self.stack = []
def push (self, p):
if p in ['+', '-', '*', '/']:
op1 = self.stack.pop ()
op2 = self.stack.pop ()
self.stack.append ('(%s %s %s)' % (op1, p, op2) )
elif p == '!':
op = self.stack.pop ()
self.stack.append ('%s!' % (op) )
elif p in ['sin', 'cos', 'tan']:
op = self.stack.pop ()
self.stack.append ('%s(%s)' % (p, op) )
else:
self.stack.append (p)
def convert (self, l):
l.reverse ()
for e in l:
self.push (e)
return self.stack.pop ()
c = Calculator ()
print c.convert ( ['+', 8, 9] )
print c.convert ( ['!', 42] )
print c.convert ( ['sin', 'pi'] )
print c.convert ( ['+', 'sin', '/', 'x', 2, 'cos', '/', 'x', 3] )