Skip to main content

Evaluate postfix expression using stack in python

Python program for Evaluate postfix expression using stack. Here problem description and explanation.

#  Python 3 program for 
#  Evaluate postfix expression

#  Stack Node
class StackNode :
	def __init__(self, operand, top) :
		self.operand = operand
		self.next = top
	

class MyStack :
	def __init__(self) :
		self.top = None
		self.count = 0
	
	#  Returns the number of element in stack
	def isSize(self) :
		return self.count
	
	def isEmpty(self) :
		if (self.isSize() > 0) :
			return False
		else :
			return True
		
	
	#  Add a new element in stack
	def push(self, value) :
		#  Make a new stack node
		#  And set as top
		self.top = StackNode(value, self.top)
		#  Increase node value
		self.count += 1
	
	#  Remove a top element 
	def pop(self) :
		value = self.peek()
		if (self.isEmpty() == False) :
			self.top = self.top.next
			#  Reduce the size
			self.count -= 1
		
		return value
	
	#  Used to get top element of stack
	def peek(self) :
		if (not self.isEmpty()) :
			return self.top.operand
		else :
			return 0
		
	

class Execution :
	def evaluate(self, e) :
		#  Get the length of expression
		size = len(e)
		a = 0
		b = 0
		s = MyStack()
		isVaild = True
		i = 0
		#  work with (+,-,/,*,%) operator
		while (i < size and isVaild) :
			if (e[i] >= '0'
				and e[i] <= '9') :
				a = ord(e[i]) - ord('0')
				s.push(a)
			elif (s.isSize() > 1) :
				a = s.pop()
				b = s.pop()
				#  Perform arithmetic operations between 2 operands
				if (e[i] == '+') :
					s.push(b + a)
				elif (e[i] == '-') :
					s.push(b - a)
				elif (e[i] == '*') :
					s.push(b * a)
				elif (e[i] == '/') :
					s.push(int(b / a))
				elif (e[i] == '%') :
					s.push(b % a)
				else :
					#  When use other operator
					isVaild = False
				
			elif (s.isSize() == 1) :
				#  Special case  
				#  When use +, - at the beginning
				if (e[i] == '-') :
					a = s.pop()
					s.push(-a)
				elif (e[i] != '+') :
					#  When not use  +,-
					isVaild = False
				
			else :
				isVaild = False
			
			i += 1
		
		if (isVaild == False) :
			#  Possible case use other operators
			#  1) When using special operators
			#  2) Or expression is invalid
			print(e ," Invalid expression ")
			return
		
		print(e ," = ", s.pop())
	

def main() :
	task = Execution()
	#  Execute the following expression
	#  (1+2)*(3+5)
	task.evaluate("12+35+*")
	#  -((7*2) + (6/2) + 4)
	task.evaluate("72*62/+4+-")

if __name__ == "__main__": main()

Output

12+35+*  =  24
72*62/+4+-  =  -21




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment