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
| class Solution: opr = {"+":0,"-":0,"*":1,"/":1,"(": -1,")": -1} def to_postfix(self,s): stack = [] res = [] i = 0 while i < len(s): if s[i] == " ": i+=1 elif s[i] not in self.opr: num = "" while i < len(s) and s[i] not in self.opr: num += s[i] i+=1 res.append(int(num)) num ="" else: if s[i] == "(": stack.append(s[i]) elif s[i] == ")": while stack[-1] != "(": op = stack.pop() res += op stack.pop() elif (not stack) or self.opr[stack[-1]] < self.opr[s[i]]: stack.append(s[i]) else: while stack and self.opr[stack[-1]] >= self.opr[s[i]]: op = stack.pop() res += op stack.append(s[i]) i += 1
while stack: res += stack.pop()
return res def calculate_postfix(self,s):
print(s)
add = lambda x,y: x+y sub = lambda x,y: x-y mul = lambda x,y: x*y div = lambda x,y: x//y
self.opr_func = {"+":add,"-":sub,"*":mul,"/":div}
stack = [] for char in s: if char not in self.opr: stack.append(int(char)) else: second = stack.pop() first = stack.pop() stack.append(self.opr_func[char](first,second))
return stack[-1] def calculate(self, s: str) -> int: if not s: return 0 return self.calculate_postfix(self.to_postfix(s))
|