Professional Documents
Culture Documents
Stack Program01
Stack Program01
(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 = []
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()
if char.isnumeric():
stack.push(char)
operand2 = stack.pop()
operand1 = stack.pop()
stack.push(result)
return stack.pop()
operand1 = int(operand1)
operand2 = int(operand2)
if operator == "+":
else:
stack = Stack()
postfix = ""
if char.isnumeric():
postfix += char
postfix += stack.pop()
stack.push(char)
stack.push(char)
postfix += stack.pop()
stack.pop()
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)
output