Python solution easy to understand


  • 0
    Z
    class Solution(object):
        def solveEquation(self, equation):
            """
            :type equation: str
            :rtype: str
            """
            def convert(left):
                val_left = 0
                coef_left = 0
                i = 0
                while i < len(left):
                    temp = ''
                    if left[i]=='+' or left[i]=='-':
                        temp+=left[i]
                        i+=1
                    #count = 0
                    #i+=1
                    while i<len(left) and left[i]!='+' and left[i]!='-' and left[i]!='x':
                        temp+=left[i]
                        i+=1
                    if i==len(left):
                        val_left += int(temp)
                        break
                    elif left[i]=='x':
                        if len(temp)==0:
                            coef_left +=1
                        elif temp[-1]=='+' or temp[-1]=='-':
                            coef_left += int(temp[-1]+'1')
                        else:
                            coef_left += int(temp)
                        i+=1
                    else:
                        val_left+=int(temp)
                return coef_left,val_left
            left,right = equation.split('=')
            coef_left,val_left=convert(left)
            coef_right,val_right=convert(right)
            if coef_left == coef_right:
                if val_left == val_right:
                    return "Infinite solutions"
                else:
                    return "No solution"
            else:
                return "x="+str((val_right-val_left)/(coef_left-coef_right))

Log in to reply
 

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