-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathh224.py
84 lines (75 loc) · 3.05 KB
/
h224.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# Terrible runtime but it passed lol
# Will redo with a stack later
# I aint proud of this code lol in hindsight I can see how much
# better it would be using the stack method
class Solution:
def calculate(self, s: str) -> int:
s = s.replace(' ', '') # strip unnecessary info
if s == '' :
return 0
if s == '-' :
return -1
# brackets first
if '(' in s :
leftIndx = s.find('(')
rightIndx = leftIndx
counter = 1
while counter > 0 :
rightIndx += 1
if s[rightIndx] == '(' :
counter += 1
elif s[rightIndx] == ')' :
counter -= 1
retVal = 0
if ('-' == s[leftIndx - 1]) : # negative before the bracket / subtraction
retVal = self.calculate(s[0:leftIndx - 1]) + \
-1 * self.calculate(s[leftIndx + 1:rightIndx]) + \
self.calculate(s[rightIndx + 1:])
else :
retVal = self.calculate(s[0:leftIndx]) + \
self.calculate(s[leftIndx + 1:rightIndx]) + \
self.calculate(s[rightIndx + 1:])
# print(s[0:leftIndx], s[leftIndx + 1:rightIndx], s[rightIndx + 1:])
return retVal
# is already just a number currently
operators = set(list('+-*/'))
if not any(op in s for op in operators) :
return int(s)
# operator present
# mult and div first from left to right
# NOTE: no brackets are present so we can just operate left to right
expression = []
currentNum = []
addMin = set(list('+-'))
for c in s :
if c in addMin :
expression.append(''.join(currentNum))
currentNum = []
if c == '-' : # treat subtractions like adding a negative number
currentNum.append('-')
else : # numeric or */
currentNum.append(c)
expression.append(''.join(currentNum)) # final value in the sequence of added vals
# sum all the values calculated
output = 0
for exp in expression :
if exp == '' :
continue
if '*' in exp or '/' in exp :
vals = list(reversed(re.split('[*/]', exp)))
operators = list(reversed(re.findall('[*/]', exp)))
while operators :
if operators.pop() == '*' :
vals.append(int(vals.pop()) * int(vals.pop()))
else :
a, b = int(vals.pop()), int(vals.pop())
print(a, b)
if (a >= 0) == (b >= 0) :
temp = a // b
else :
temp = -1 * (abs(a) // abs(b))
vals.append(temp)
output += vals.pop()
else :
output += int(exp)
return output