Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Basic Calculator II in Python
A basic calculator evaluates mathematical expressions containing non-negative integers and operators (+, -, *, /). The calculator must handle operator precedence correctly, where multiplication and division are performed before addition and subtraction.
For the input "3+2*2", the output should be 7 because multiplication has higher precedence than addition.
Algorithm Approach
We use a stack-based approach to handle operator precedence ?
- Remove spaces from the expression
- Use a stack to store intermediate results
- Process multiplication and division immediately
- Store addition and subtraction operands for later summation
Implementation
class Solution:
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
stack = []
i = 0
x = ""
# Remove spaces
for j in s:
if j != " ":
x += j
s = x
n = len(s)
while i < n:
if s[i] == '/':
i += 1
num, i = self.make_num(s, i)
if stack[-1] < 0:
stack[-1] = -1 * (abs(stack[-1]) // num)
else:
stack[-1] = stack[-1] // num
elif s[i] == '*':
i += 1
num, i = self.make_num(s, i)
stack[-1] = stack[-1] * num
elif s[i] == '-':
i += 1
num, i = self.make_num(s, i)
stack.append(-num)
elif s[i] == '+':
i += 1
num, i = self.make_num(s, i)
stack.append(num)
else:
num, i = self.make_num(s, i)
stack.append(num)
i += 1
return sum(stack)
def make_num(self, s, i):
start = i
while i < len(s) and s[i] not in ['/', '*', '-', '+']:
i += 1
return int(s[start:i]), i - 1
# Test the calculator
solution = Solution()
result = solution.calculate("3+2*2")
print(result)
7
How It Works
The algorithm processes the expression character by character ?
- Multiplication/Division: Performed immediately by modifying the top stack element
- Addition/Subtraction: Operands are pushed to the stack (negative for subtraction)
- Final Result: Sum all elements in the stack
Example Walkthrough
For expression "3+2*2" ?
solution = Solution()
# Step-by-step trace
expressions = ["3", "3+2", "3+2*2", "14-3*2", "2*3+1"]
for expr in expressions:
result = solution.calculate(expr)
print(f"'{expr}' = {result}")
'3' = 3 '3+2' = 5 '3+2*2' = 7 '14-3*2' = 8 '2*3+1' = 7
Key Features
- Operator Precedence: Multiplication and division are handled immediately
- Integer Division: Uses floor division (//) for integer results
- Stack Management: Efficiently handles intermediate calculations
- Space Removal: Preprocesses input to remove whitespace
Conclusion
This stack-based calculator correctly handles operator precedence by immediately processing multiplication and division operations. The final result is obtained by summing all stack elements, ensuring accurate evaluation of mathematical expressions.
