Easy to understand concise Python code with (a bit) explanations.


  • 0
    X

    Idea is straightforward: firstly get a "number" (function get_number), and then using a loop to continuously get one operator (o) and the second "number". Do the calculation, then done.

    Now let's define what is a "number", it can be either an actual number (like 5) or a term. E.g., (5+6+2)+3, we'll treat (5+6+2) as a number. So once we see a "(", we recursively call the main function (calculate_helper), which will return the value of 5+6+2 and the location of the ")", now we get the "number" of "(5+6+2)".

    I don't like the way I handle skip() the spaces. Maybe it can be optimized to shorten the code.

        def skip(self, s, i):
            while i < len(s) and s[i] == " ": i += 1
            return i
        def get_number(self, s, i):
            i = self.skip(s, i)
            if i < len(s) and s[i] == "(":
                return self.calculate_helper(s, i + 1)
            else:
                t = i
                while i < len(s) and s[i].isdigit(): i += 1
                return int(s[t:i]), self.skip(s, i)
        def calculate_helper(self, s, i):
            r, i = self.get_number(s, i)
            while i < len(s) and s[i] != ")":
                o = s[i]
                n, i = self.get_number(s, i + 1)
                r += n * (1 if o == "+" else -1)
            return r, self.skip(s, i + 1)
        def calculate(self, s):
            return self.calculate_helper(s, 0)[0]
    

Log in to reply
 

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