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?
foo = ['+', x, y], the expression[foo[1], foo[0], foo[2]]will result in[x, '+', y]. Isn't that what you want? In case of nested expressions, you'd have to do simple recursion. Maybe you should give a clearer and more complex example of your input and expected output.['+', 2, 3, 4, 5]would yield2 + 3 + 4 + 5