Python, Straightforward with Explanation

  • 1

    Our goal is to get the coefficients of A and B in the reduced equation Ax+B=0. From there, we can read off the answer.

    Every time we find a + or -, we should change our sign. This sign is reversed if we have already seen the =. Otherwise, we should parse the word appropriately: if it ends with an x, then it is a coefficient of x, otherwise it is a constant.

    def solveEquation(self, equation):
        left = True
        sign = 1
        A = B = 0
        for k, v in itertools.groupby(equation, key = lambda x: x in '+-='):
            w = "".join(v)
            if k:
                for x in w:
                    if x == '=': left = False
                    sign = 1 if x != '-' else -1
                    sign *= 1 if left else -1
                if w[-1] == 'x':
                    A += sign * (int(w[:-1]) if w[:-1] else 1)
                    B += sign * int(w)
        if A == B == 0:
            return "Infinite solutions"
        elif A == 0:
            return "No solution"
            return "x={}".format(-B/A)

Log in to reply

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