Infix to Postfix Due Thursday 02232017 at 1159PM Use the sta
Solution
# inToPost.py
from Stack import Stack
 # Python program to convert infix expression to postfix
 
 # Class to convert the expression
 class Conversion:
 
 # Constructor to initialize the class variables
 def __init__(self):
 self.stack = Stack()
 # Precedence setting
 self.output = Stack()
 self.precedence = {\'+\':1, \'-\':1, \'*\':2, \'/\':2, \'^\':3}
 
 # A utility function to check is the given character
 # is operand
 def isOperand(self, ch):
 return ch.isalpha()
 
 # Check if the precedence of operator is strictly
 # less than top of stack or not
 def notGreater(self, i):
 try:
 a = self.precedence[i]
 b = self.precedence[self.stack.top()]
 return True if a <= b else False
 except KeyError:
 return False
 
 # The main function that converts given infix expression
 # to postfix expression
 def inToPost(self, exp):
 
 # Iterate over the expression for conversion
 for i in exp:
 # If the character is an operand,
 # add it to output
 if i.isspace():
 continue
 if self.isOperand(i):
 self.output.push(i)
 
 # If the character is an \'(\', push it to stack
 elif i == \'(\':
 self.stack.push(i)
 
 # If the scanned character is an \')\', pop and
 # output from the stack until and \'(\' is found
 elif i == \')\':
 while( (not self.stack.isEmpty()) and self.stack.top() != \'(\'):
 a = self.stack.top()
 self.stack.pop()
 self.output.push(a)
 if (not self.stack.isEmpty() and self.stack.top() != \'(\'):
 return -1
 else:
 self.stack.pop()
 
 # An operator is encountered
 else:
 while(not self.stack.isEmpty() and self.notGreater(i)):
 self.output.push(self.stack.top())
 self.stack.pop()
 self.stack.push(i)
 
 # pop all the operator from the stack
 while not self.stack.isEmpty():
 self.output.push(self.stack.top())
 self.stack.pop()
 
 result = []
 while not self.output.isEmpty():
 result.append(self.output.top())
 self.output.pop()
 print \" \".join(result)
 
 # Driver program to test above function
 exp = \"a + b * ( c ^ d - e ) ^ ( f + g * h ) - i\"
 obj = Conversion()
 obj.inToPost(exp)
# Stack.py
class Stack(object):
 def __init__(self):
 self.items = []
   
 # Push the element to the stack
 def push(self, item):
 self.items.append(item)
   
 # Pop the element from the stack
 def pop(self):
 if not self.isEmpty():
 self.items.pop()
   
 # top the element from the stack
 def top(self):
 return self.items[-1]
   
 # return size of stack
 def size(self):
 return len(self.items)
   
 def isEmpty(self):
 if self.size() == 0:
 return True
 else:
 return False
Code link
https://goo.gl/2dHaPc



