wever, you can also modify the code for what is best by using two def functions for the push and pop. Moreover, can you also please add some one-liner explanations on how the code works, starting from the first 'for loop' until the 'last while loop'? I am still studying Python so, please bare with me. Thanks!
I have the infix to postfix stack code below, it works perfectly fine; however, can you please help me to stop using .push() and .pop() by using def functions for each? Then, instead of using the .pop() and .push() can you just call the def functions? However, you can also modify the code for what is best by using two def functions for the push and pop. Moreover, can you also please add some one-liner explanations on how the code works, starting from the first 'for loop' until the 'last while loop'? I am still studying Python so, please bare with me. Thanks!
Operators=set(['+', '-', '*', '/', '(', ')', '^'])
Priority={'+':1, '-':1, '*':2, '/':2, '^':3}
def infixToPostfix(expr):
stack =[]
out= ''
for i in expr:
if i not in Operators:
out+=i
elif i=='(':
stack.append('(')
elif i==')':
while stack and stack[-1]!= '(':
out+=stack.pop()
stack.pop()
else:
while stack and stack[-1]!='(' and Priority[i]<=Priority[stack[-1]]:
out+=stack.pop()
stack.append(i)
print(out)
while stack:
out+=stack.pop()
print(out)
return out
expr='A*(B*C+D*E)+F'
print('Infix expression: ',expr)
print('Postfix expression: ',infixToPostfix(expr))
Step by step
Solved in 4 steps with 3 images