# basic calculation with negative support
class Solution:
    # @param {string} s
    # @return {integer}
    def calculate(self, s):
        pre, stack, temp, total, isNeg = 1, [], 0, 0, 1
        # don't forget this
        stack.append(pre)
        # 1 - 2, 1 + (-2),-3+9
        for idx, va in enumerate(s):
            if va == '(':
                stack.append(pre)
            elif va == ')':
                stack.pop()
            elif va in '+-':
                if va == '+':
                    total += pre * temp
                    # remember to reset is neg
                    # for "1-(-2+1)", when we saw '+', then isNeg need to be reset
                    pre, isNeg = stack[-1], 1
                else:
                    # for ex 5-6, if '-' has digit on its left, the it is an operator
                    if idx and s[idx - 1].isdigit():
                        total += pre * temp
                        # 1-(-2-1) , if we saw '-' in front of 1, then we need reset isNeg
                        pre, isNeg = -1 * stack[-1], 1
                    # if -3+5 or 5-(-3+6)
                    else:
                        isNeg = -1

                temp = 0

            else:
                temp = temp * 10 + isNeg * int(va)

        return total + pre * temp


if __name__ == '__main__':
    print Solution().calculate("1-(-2)")
    print Solution().calculate("1--2")
    print Solution().calculate("1-(-2+1)")
    print Solution().calculate("-1-(-2+1)")
