Code Patterns
Basic Calculator
Code Pattern
Get Number
get_number
: Reads and converts a sequence of digits from the string into an integer.
Update Stack
update_stack
: Modifies the stack based on the arithmetic operation specified, enabling the evaluation of expressions in a structured manner.- Addition: If the operator is
+
, it appends num to the stack. - Subtraction: If the operator is
-
, it appends -num to the stack to account for the negative value. - Multiplication: If the operator is
*
, it pops the top value from the stack, multiplies it by num, and appends the result back to the stack. - Division: If the operator is
/
, it pops the top value, performs integer division with num, and appends the result back to the stack (using int to ensure integer division).
- Addition: If the operator is
Calculate
- Character Processing
- If the character is a digit, it retrieves the full number.
- If it encounters a
(
, it recursively calls calc() to evaluate the expression inside. - If it sees a
)
, it updates the stack with the current num and operator, then returns the sum of the stack. - For operators (
+
,-
,*
,/
), it updates the stack with the current number and operator, sets the new operator, and resets num.
def calculate(self, s: str) -> int:self.index = 0def get_number():num = 0while self.index < len(s) and s[self.index].isdigit():num = num * 10 + int(s[self.index])self.index += 1return num
Common mistakes
- Forget to reset num after an operator
# Wrong: Forgetting to reset num after processing an operatorelif char in '+-*/':update_stack(stack, num, operator)# num is not reset here, leading to incorrect calculations# Correct:elif char in '+-*/':update_stack(stack, num, operator)operator = charnum = 0 # Reset num for the next number
Related Problem
class Solution:def calculate(self, s: str) -> int:self.index = 0def get_number():# Use the code abovedef update_stack(stack, num, operator):# Use the code abovedef calc():# Use the code abovereturn calc()
class Solution:def calculate(self, s: str) -> int:self.index = 0def get_number():# Use the code abovedef update_stack(stack, num, operator):# Use the code abovedef calc():# Use the code abovereturn calc()
class Solution:def calculate(self, s: str) -> int:self.index = 0def get_number():# Use the code abovedef update_stack(stack, num, operator):# Use the code abovedef calc():# Use the code abovereturn calc()