-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpostfix.py
More file actions
25 lines (21 loc) · 836 Bytes
/
Copy pathpostfix.py
File metadata and controls
25 lines (21 loc) · 836 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
def evaluate_postfix(expression):
stack = []
for token in expression.split():
if token.isdigit(): # If token is a number, push it to the stack
stack.append(int(token))
else: # If token is an operator, pop two operands and apply the operation
b = stack.pop()
a = stack.pop()
if token == '+':
stack.append(a + b)
elif token == '-':
stack.append(a - b)
elif token == '*':
stack.append(a * b)
elif token == '/':
stack.append(int(a / b)) # Integer division
return stack.pop()
# Example usage
expression = "5 1 2 + 4 * + 3 -" # Equivalent to: (5 + ((1 + 2) * 4)) - 3
result = evaluate_postfix(expression)
print("Result:", result)