Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

Stack program.

(01)
Example of a program that uses a stack to evaluate arithmetic expressions
using user input in Python:

Code :
class Stack:

def __init__(self):

self.items = []

def push(self, item):

self.items.append(item)

def pop(self):

if not self.is_empty():

return self.items.pop()

def is_empty(self):

return len(self.items) == 0

def peek(self):

if not self.is_empty():

return self.items[-1]

def evaluate_expression(expression):
stack = Stack()

for char in expression:

if char.isnumeric():

stack.push(char)

elif char in ["+", "-", "*", "/"]:

operand2 = stack.pop()

operand1 = stack.pop()

result = perform_operation(char, operand1, operand2)

stack.push(result)

return stack.pop()

def perform_operation(operator, operand1, operand2):

operand1 = int(operand1)

operand2 = int(operand2)

if operator == "+":

return operand1 + operand2

elif operator == "-":

return operand1 - operand2

elif operator == "*":

return operand1 * operand2

else:

return operand1 / operand2


def infix_to_postfix(expression):

precedence = {"+": 1, "-": 1, "*": 2, "/": 2}

stack = Stack()

postfix = ""

for char in expression:

if char.isnumeric():

postfix += char

elif char in ["+", "-", "*", "/"]:

while (not stack.is_empty()) and (precedence[char] <=


precedence[stack.peek()]):

postfix += stack.pop()

stack.push(char)

elif char == "(":

stack.push(char)

elif char == ")":

while not stack.is_empty() and stack.peek() != "(":

postfix += stack.pop()

stack.pop()

while not stack.is_empty():

postfix += stack.pop()

return postfix

while True:
expression = input("Enter an arithmetic expression in infix notation
(e.g. 1 + 2 * 3): ")

postfix = infix_to_postfix(expression)

result = evaluate_expression(postfix)

print("Result: ", result)

output

You might also like