forked from PriyankaKhire/ProgrammingPracticePython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBasic Calculator III.py
More file actions
93 lines (81 loc) · 2.72 KB
/
Basic Calculator III.py
File metadata and controls
93 lines (81 loc) · 2.72 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# Basic Calculator III
# https://leetcode.com/problems/basic-calculator-iii/
class Calculator(object):
def __init__(self):
self.operators = ['+', '-', '*', '/']
def addition(self, a, b):
return a+b
def subtraction(self, a, b):
return a-b
def multiplacation(self, a, b):
return a*b
def division(self, a, b):
if (a == 0 or b == 0):
return 0
return a/(b)
def operation(self, a, b, operator):
expressions = {
'+': self.addition(a, b),
'-': self.subtraction(a, b),
'*': self.multiplacation(a, b),
'/': self.division(a, b)
}
return expressions[operator]
def precedence(self, operator):
precidence = {
'*':1,
'/':1,
'+':0,
'-':0,
}
return precidence[operator]
class Solution(object):
def convertInToList(self, s):
newList = []
number = ""
for char in list(s):
if char.isnumeric():
number = number + char
else:
if (number != ""):
newList.append(int(number))
number = ""
newList.append(char)
return newList
def calculate(self, s):
s = s+')'
s = self.convertInToList(s)
numStack = []
operatorStack = ['(']
calculator = Calculator()
for char in s:
print numStack, operatorStack
if(char == '('):
operatorStack.append(char)
elif(char == ')'):
while(operatorStack and operatorStack[-1] != '('):
n2 = numStack.pop()
n1 = numStack.pop()
op = operatorStack.pop()
print "number1", n1, "number2", n2, "operator", op
ans = calculator.operation(n1, n2, op)
numStack.append(ans)
# pop "("
if operatorStack:
operatorStack.pop()
elif(char in calculator.operators):
operatorStack.append(char)
else:
ans = char
while(operatorStack and operatorStack[-1] == '*' or operatorStack[-1] == '/'):
op = operatorStack.pop()
num = numStack.pop()
print "current num", ans, "top of stack", num, "operator", op,
ans = calculator.operation(num, ans, op)
print "answer", ans
numStack.append(ans)
return int(numStack[-1])
"""
:type s: str
:rtype: int
"""