Simple 2-liner (and more)


  • 12
    def solve_equation(equation)
      a, x = eval('i = 1i;' + equation.gsub('x', 'i').sub('=', '-(') + ')').rect
      "x=#{-a/x}" rescue a != 0 ? 'No solution' : 'Infinite solutions'
    end
    

    It's easy to change an equation like 2+3x=5x-7 to an expression for a complex number like 2+3i-(5i-7). Then I let Ruby evaluate that and it gives me the total of "x numbers" and the total of "non-x numbers" as the imaginary and real part of the complex number.

    Same in Python:

    def solveEquation(self, equation):
        z = eval(equation.replace('x', 'j').replace('=', '-(') + ')', {'j': 1j})
        a, x = z.real, -z.imag
        return 'x=%d' % (a / x) if x else 'No solution' if a else 'Infinite solutions'
    

    And here's a completely different one using a regular expression to parse the tokens:

    def solveEquation(self, equation):
        x = a = 0
        side = 1
        for eq, sign, num, isx in re.findall('(=)|([-+]?)(\d*)(x?)', equation):
            if eq:
                side = -1
            elif isx:
                x += side * int(sign + '1') * int(num or 1)
            elif num:
                a -= side * int(sign + num)
        return 'x=%d' % (a / x) if x else 'No solution' if a else 'Infinite solutions'

Log in to reply
 

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