-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
67 lines (42 loc) · 957 Bytes
/
main.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
from collections import deque
def doOp(a,b,op):
if op == '+':
return a + b
else:
return a - b
def evaluate(expression):
stack = deque()
ops = deque()
currOp = "+"
i = 0
while i < len(expression):
currChar = expression[i]
if currChar.isdigit():
num = ""
while i < len(expression) and expression[i].isdigit():
num += expression[i]
i+=1
i -= 1
prev = 0
if len(stack):
prev = stack.pop()
currVal = doOp(prev, int(num), currOp)
stack.append(currVal)
elif currChar == '(':
ops.append(currOp)
stack.append(0)
currOp = '+'
elif currChar == ')':
currOp = ops.pop()
b = stack.pop()
a = stack.pop()
currVal = doOp(a,b,currOp)
stack.append(currVal)
else:
currOp = currChar
i+=1
return stack.pop()
def main():
print evaluate("5-(4-3)")
if __name__ == '__main__':
main()