from linked_stack import LinkedStack
def infix2postfix(expression):
output = []
op_stack = LinkedStack()
op_priority = {'*': 2, '/': 2, '%': 2, '+': 1, '-': 1, '(': 0, ')': 0}
for e in expression:
if e == '(':
op_stack.push(e)
elif e == ')':
while op_stack.first() != '(':
output.append(op_stack.pop())
op_stack.pop()
elif e.isdigit():
output.append(e)
else:
while not op_stack.is_empty() and op_priority[op_stack.first()] >= op_priority[e]:
output.append(op_stack.pop())
op_stack.push(e)
while not op_stack.is_empty():
output.append(op_stack.pop())
return ''.join(output)
def postfix_eval(expression):
num_stack = LinkedStack()
for e in expression:
if e.isdigit():
num_stack.push(e)
else:
num1 = num_stack.pop()
num2 = num_stack.pop()
res = eval(num2 + e + num1)
num_stack.push(str(res))
return num_stack.pop()
if __name__ == "__main__":
print(infix2postfix('2+(3+5)*(6+4)*(8+3)'))
print(postfix_eval('235+64+*83+*+'))