forked from MTrajK/coding-problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic_calculator.py
More file actions
69 lines (53 loc) · 1.65 KB
/
basic_calculator.py
File metadata and controls
69 lines (53 loc) · 1.65 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
'''
Basic Calculator
Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open '(' and closing parentheses ')',
the plus '+' or minus sign '-', non-negative integers and empty spaces ' '.
Input: '(1+(4+5+2)-3)+(6+8)'
Output: 23
Input: ' 2-1 + 2 '
Output: 3
=========================================
Start from the first character and respect the math rules. When brackets come, go inside the brackets
and compute the inner result, after that continue with adding or subtracting.
Time Complexity: O(N)
Space Complexity: O(K) , much less than N (the deepest level of brackets)
'''
############
# Solution #
############
def basic_calculator(s):
return calculate(s, 0)[0]
def calculate(s, i):
sign = 1 # 1 means '+' and -1 means '-'
res = 0
num = 0
while i < len(s) and s[i] != ')':
if s[i] >= '0' and s[i] <= '9':
# find the whole number
num = num * 10 + int(s[i])
elif s[i] == '(':
# calculate inside the brackets
brackets = calculate(s, i + 1)
res += brackets[0] * sign
i = brackets[1] # continue from the new i
elif s[i] != ' ':
# add the previous number using the old sign
res += num * sign
num = 0
if s[i] == '-':
sign = -1
elif s[i] == '+':
sign = 1
i += 1
res += num * sign
return (res, i)
###########
# Testing #
###########
# Test 1
# Correct result => 23
print(basic_calculator('(1+(4+5+2)-3)+(6+8)'))
# Test 2
# Correct result => 3
print(basic_calculator(' 2-1 + 2 '))