Elementary School Math approach in python


  • 0
    S
    import re
    class Solution(object):
        def solveEquation(self, equation):
            """
            :type equation: str
            :rtype: str
            """
            res = ''
            if equation:
                # split equation in left and right hand side!
                leftHandSide,rightHandSide = equation.split('=')
                
                # collect all x terms on right hand side
                right_xterms =  re.findall(r'[-+]?[\d]*x\b',rightHandSide)
                # collect all numbers on right hand side
                right_numbers = re.findall(r'[-+]?[\d]+\b',rightHandSide)
                
                # collect all x terms on left hand side
                left_xterms  = re.findall(r'[-+]?[\d]*x\b',leftHandSide)
                # collect all numbers on left hand side
                left_numbers = re.findall(r'[-+]?[\d]+\b',leftHandSide)
                
                # replace all x with 1 if no multiplier of else remove x for both left and right x terms
                right_xterms = list(map(lambda x: int(x.replace('x','')) if re.match(r'[-+]?[\d]+x',x) else int(x.replace('x','1')), right_xterms))
                left_xterms  = list(map(lambda x: int(x.replace('x','')) if re.match(r'[-+]?[\d]+x',x) else int(x.replace('x','1')), left_xterms))
                
                # final xterm, moved all x to left ( this is number of x's left on left side of equation)
                final_xterm = sum(left_xterms) - sum(right_xterms)
                
                # moved all numbers to right, and did math
                final_number = sum(map(int,right_numbers)) - sum(map(int,left_numbers))
                
                # if 0 on left side but non zero on right side
                if final_xterm == 0 and final_number != 0:
                    return "No solution"
                
                # if 0 on left side and 0 on right side, any value of x will solve
                if final_xterm == 0 and final_number == 0:
                    return "Infinite solutions"
                
                # divide right hand side with multiple of x
                res = "x=" + str(final_number/final_xterm)
            return res

Log in to reply
 

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