0% found this document useful (0 votes)
115 views

Python Program To Evaluate A Postfix Expression Using A Stack.

Uploaded by

Bishwajit Salam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
115 views

Python Program To Evaluate A Postfix Expression Using A Stack.

Uploaded by

Bishwajit Salam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

python program to evaluate a postfix expression using a stack.

def evaluate_postfix(expression):

stack = []

def is_operand(char):

return char.isnumeric()

def apply_operator(operator, operand1, operand2):

if operator == '+':

return operand1 + operand2

elif operator == '-':

return operand1 - operand2

elif operator == '*':

return operand1 * operand2

elif operator == '/':

return operand1 / operand2

elif operator == '^':

return operand1 ** operand2

for char in expression:

if is_operand(char):

stack.append(int(char))

else:

operand2 = stack.pop()

operand1 = stack.pop()

result = apply_operator(char, operand1, operand2)

stack.append(result)

if len(stack) == 1:
return stack[0]

else:

print("Invalid postfix expression. More than one value left in the stack.")

# Example Usage:

postfix_expression = "235*+"

result = evaluate_postfix(postfix_expression)

print(f"Result of {postfix_expression} is: {result}")

Output:

Result of 235*+ is: 17

You might also like