defcalculate2(self, s): """ 1. Take 3 containers: num -> to store current num value only sign -> to store sign value, initially +1 res -> to store sum When ( comes these containers used for calculate sum of intergers within () brackets. -------------------- 2. When c is + or - Move num to res, because we need to empty num for next integer value. set num = 0 sign = update with c -------------------- 3. When c is '(' Here, we need num, res, sign to calculate sum of integers within () So, move num and sign to stack => [num, sign] Now reset - res = 0, num = 0, sign = 1 (default) -------------------- 4. When c is ')' -> 2-(3+4), Here res=3, num=4, sign=1 stack [2, -] res +=sign*num -> calculate sum for num first, then pop items from stack, res=7 res *=stack.pop() - > Pop sign(+ or -) to multiply with res, res = 7*(-1) res +=stack.pop() - > Pop integer and add with prev. sum, res = -7 + 2 - 5 -------------------- Simple Example: 2 - 3 Initially res will have 2,i.e. res = 2 then store '-' in sign. it will be used when 3 comes. ie. sign = -1 Now 3 comes => res = res + num*sign Return statement: res+num*sign => res = 2 + 3(-1) = 2 - 3 = -1 """ num = 0 sign = 1 res = 0 stack = [] for i inrange(len(s)): # iterate till last character c = s[i] if c.isdigit(): # process if there is digit num = num * 10 + int(c) # for consecutive digits 98 => 9x10 + 8 = 98 elif c in'-+': # check for - and + sign,如果沒遇到括號,就繼續計算res總額 res += num * sign sign = -1if c == '-'else1 num = 0 elif c == '(': # if ( comes, 儲存括號以外的總額,與括號之前的符號 stack.append(res) stack.append(sign) res = 0# reset res for new calculation sign = 1 elif c == ')': # if ) comes, 括號結束的意思,可以把 stack 的內容取出來計算 res += sign * num res *= stack.pop() res += stack.pop() num = 0 return res + num * sign