Why my codes cannot pass all the test cases?


  • -1
    X
    class Solution(object):
        def calculate(self, s):
            """
            :type s: str
            :rtype: int
            """
            number,op = [],[]
            tmp = ''
            for i in range(len(s)):
                
                if s[i].isdigit():
                    tmp+=s[i]
                    if i == len(s)-1 or not s[i+1].isdigit():
                        number.append(int(tmp))
                        print number
                        tmp = ''
                elif s[i] in '(+-':
                    op.append(s[i])
                elif s[i] == ')':
                    while op[-1]!='(':
                        self.compute(number,op)
                    op.pop()
            while op:
                self.compute(number,op)
            return number[-1]
            
            
        def compute(self,number,op):
            a,b = number.pop(),number.pop()
            opr = op.pop()
            if opr == '+':
                number.append(a+b)
            if opr == '-':
                number.append(b-a)

  • 0

    Slight modification to your code which works fine. Please check the below code:

    def compute(self, num, op):
        a, b=num.pop(), num.pop()
        l=len(op)
        asign=op.pop()
        if l==1 or op[-1]=="(":
            if asign=="+":
                num.append(a+b)
            elif asign=="-":
                num.append(b-a)
            return
    
        bsign= op.pop()
        if asign == bsign:
            num.append(a+b)
            op.append(asign)
        elif asign!=bsign:
            if a > b:
                num.append(a-b)
                op.append(asign)
            elif b > a:
                num.append(b-a)
                op.append(bsign)
        
    
    def calculate(self, s):
        """
        :type s: str
        :rtype: int
        """
        num, op=[],[]
        n=len(s)
        tmp=""
        for i in range(n):
            if s[i].isdigit():
                tmp+=s[i]
                if i==n-1 or not s[i+1].isdigit():
                    num.append(int(tmp))
                    tmp=""
            elif s[i] in "(+-":
                op.append(s[i])
            elif s[i]==")":
                while op[-1]!="(":
                    self.compute(num,op)
                op.pop()
        
        while op:
            self.compute(num, op)
        
        return num[-1]

  • 0
    X

    Could you please explain the compute() function?


  • 0

    Basically, your compute function had problem in calculating case like 7 -3+2, in this case your compute function contains 7-5=2, but actually you need to take care of the integer sign also, so it should compute 7-1=6. That is why you need to take asign and bsign, and compute the result accordingly and store the sign again back to op list.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.