-
Notifications
You must be signed in to change notification settings - Fork 1
/
BasicCalculator.py
68 lines (50 loc) · 1.51 KB
/
BasicCalculator.py
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
# Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation.
# Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().
def doMath(stack):
total = int(stack[0])
for i in range(1, len(stack), 2):
if stack[i] == "+":
total += int(stack[i + 1])
else:
total -= int(stack[i + 1])
return total
def consolidateNums(stack):
curNum = ''
newStack = []
for i in stack:
if i == "+" or i == "-":
if curNum == '':
curNum = "0"
newStack.append(curNum)
newStack.append(i)
curNum = ''
else:
curNum += str(i)
if curNum == '':
curNum = "0"
newStack.append(curNum)
return newStack
def calculate(s):
stack = []
s = s.replace(" ", '')
for i in s:
if i == ")":
curStack = []
while stack and stack[-1] != "(":
curStack.append(stack.pop())
stack.pop()
stack.append(doMath(consolidateNums(curStack[::-1])))
else:
stack.append(i)
return doMath(consolidateNums(stack))
# Test cases
s = "1 + 1"
print(calculate(s))
s = " 2-1 + 2 "
print(calculate(s))
s = "(1+(4+5+2)-3)+(6+8)"
print(calculate(s))
s = "2147483647"
print(calculate(s))
s = "1-( -2)"
print(calculate(s))