Python with listcomp


  • 0
    W

    The basic idea is to use lists to save coefficients of x and constants separately.

    class Solution(object):
      def solveEquation(self, equation):
        """
        :type equation: str
        :rtype: str
        """
        lhs = equation.split('=')[0]
        rhs = equation.split('=')[1]
    
        lhs = lhs.replace('+', ' +').replace('-', ' -').split(' ')
        rhs = rhs.replace('+', ' +').replace('-', ' -').split(' ')
    
        lhs = [s.replace('x', '1x') if s == 'x' or s == '+x' else s for s in lhs] # x -> 1x
        rhs = [s.replace('x', '1x') if s == 'x' or s == '+x' else s for s in rhs] # x -> 1x
    
        lhs = [s.replace('-x', '-1x') if s == '-x' else s for s in lhs] # -x -> -1x
        rhs = [s.replace('-x', '-1x') if s == '-x' else s for s in rhs] # -x -> -1x
    
        lhs_coef_x = [eval(s.replace('x', '')) if 'x' in s else 0 for s in lhs]
        lhs_const = [0 if 'x' in s or s == '' else eval(s) for s in lhs]
    
        rhs_coef_x = [eval(s.replace('x', '')) if 'x' in s else 0 for s in rhs]
        rhs_const = [0 if 'x' in s or s == '' else eval(s) for s in rhs]
    
        coef_x = sum(lhs_coef_x) - sum(rhs_coef_x)
        const = sum(rhs_const) - sum(lhs_const)
    
        if coef_x == 0 and const == 0:
          return "Infinite solutions"
        elif coef_x == 0 and const != 0:
          return "No solution"
        else:
          return 'x=' + str(int(const/coef_x))
    
    

Log in to reply
 

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