easy-to-read python solution, beats 100%


  • 0
    F
    def calculate(self, s):
        sum, prod = 0, None
        op1, op2, num = None, None, 0
      
        def evalSum(prod, sum, op1, op2):
            prod = 1 if prod == None else prod
            prod = prod / num if op2 == '/' else prod * num 
            return sum - prod if op1 == '-' else sum + prod
    
        def evalProd(prod, sum, op1, op2):
            prod = 1 if prod == None else prod
            return prod / num if op2 == '/' else prod * num
    
        for c in s:
            if c.isdigit():
                num = num * 10 + ord(c) - ord('0')
            elif c in "+-":
                sum = evalSum(prod, sum, op1, op2)
                prod = None
                op1, op2, num = c, None, 0
            elif c in "*/":
                prod = evalProd(prod, sum, op1, op2)
                op2, num = c, 0
        return evalSum(prod, sum, op1, op2)
    

Log in to reply
 

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