python 3 prefix to infix without too many parethesis
jezkator at gmail.com
jezkator at gmail.com
Mon Dec 9 06:21:55 EST 2019
Hi, I have got a problem.
I wrote a code for prefix to infix. It works, but I need improve it
so on input there will be only necessary parentheses. Can u help me?
Here is the code:
import re
a = input()
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))
print("op1 =", op1)
print("op2 =", op2)
print("p=", p)
print(self.stack)
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 (re.findall(r'\d+|\*\*|[-+*/]', a)))
input is like /-*+*++**85 27 39 87 65 65 37 63 91
More information about the Python-list
mailing list