-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCalculator.py
More file actions
43 lines (37 loc) · 1.2 KB
/
Copy pathCalculator.py
File metadata and controls
43 lines (37 loc) · 1.2 KB
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
def calculate(expression):
operands = []
operators = []
# Helper function for performing the calculation
def perform_operation():
operator = operators.pop()
right = operands.pop()
left = operands.pop()
if operator == '+':
result = left + right
else:
result = left - right
operands.append(result)
# Remove whitespaces from expression
expression = expression.replace(' ', '')
# Start parsing the expression
num = ''
for char in expression:
if char.isdigit():
num += char
else:
operands.append(int(num))
num = ''
if char in '+-':
while operators and operators[-1] != '(':
perform_operation()
operators.append(char)
elif char == '(':
operators.append(char)
elif char == ')':
while operators and operators[-1] != '(':
perform_operation()
operators.pop()
operands.append(int(num)) # Add the last number to the operands list
while operators:
perform_operation()
return operands[0]