Python Solution


  • 0
    Y
    class Solution(object):
        def solveEquation(self, equation):
            """
            :type equation: str
            :rtype: str
            """
            l, r = equation.split('=')
            l, r = self.calc(l), self.calc(r)
            if l[0] == r[0] and l[1] == r[1]:
                return "Infinite solutions"
            if l[0] == r[0] and l[1] != r[1]:
                return "No solution"
            return 'x='+str((r[1] - l[1])//(l[0] - r[0]))
            
        def calc(self, string):
            x, total = 0, 0
            l = string.split('+')
            for i in range(len(l)):
                if '-' in l[i]:
                    l[i] = l[i].split('-')
            while l:
                item = l.pop()
                if isinstance(item, list):
                    for i in range(len(item)):
                        if i == 0:
                            if 'x' in item[i]:
                                x += int(item[i][:-1]) if len(item[i]) > 1 else 1
                            else:
                                total += int(item[i]) if item[i] else 0
                        else:
                            if 'x' in item[i]:
                                x -= int(item[i][:-1]) if len(item[i]) > 1 else 1
                            else:
                                total -= int(item[i])
                else:
                    if 'x' in item:
                        x += int(item[:-1]) if len(item) > 1 else 1
                    else:
                        total += int(item)
            return (x, total)
    

Log in to reply
 

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