Why is my python code too slow?


  • 0
    M

    I don't believe that I'm doing anything silly like appending to the start of a list. But this exceeds the time limit. Everything looks greedy to me, except for get_equation_elements, which has some inefficient string concatenation, but not that inefficient.

    class Solution:
        # @param {string} s
        # @return {integer}
        def calculate(self, s):
            current_sum = 0
            for num, preceded_by_neg in self.get_num_operators(s):
                if not preceded_by_neg:
                    current_sum += num
                else:
                    current_sum -= num
            return current_sum
        
        def get_num_operators(self, s):
            is_opposite = [False] # Stack of whether parenthesis preceded by negative
            preceded_by_neg = False
            for eq_elem in self.get_equation_elements(s):
                if eq_elem == '(':
                    is_opposite.append(preceded_by_neg)
                elif eq_elem == ')':
                    is_opposite.pop()
                elif eq_elem == '-':
                    preceded_by_neg = True
                elif eq_elem == '+':
                    preceded_by_neg = False
                else:
                    yield (eq_elem, preceded_by_neg != is_opposite[-1])               
        
        def get_equation_elements(self, s):
            num_string = ""
            for elem in s:
                if elem == ' ':
                    continue
                if elem == '(' or elem == ')':
                    yield elem
                    continue
                if elem == '+' or elem == '-':
                    yield int(num_string)
                    yield elem
                    continue
                num_string += elem
            yield int(num_string)

Log in to reply
 

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