Python simple and straight forward


  • 0
    D
    class Solution(object):
        def solveEquation(self, equation):
            """parse left and right part of equation, and merge
            total number of x and sum of int.
            """
            left, right = equation.split('=')
            left_x, left_num = self.parse(left)
            right_x, right_num = self.parse(right)
            total_x = left_x - right_x
            total_num = right_num - left_num
            if total_x == 0:
                if total_num != 0:
                    return 'No solution'
                else:
                    return 'Infinite solutions'
            return 'x={}'.format(total_num/total_x)
        
        def parse(self, string):
            """return number of x and sum of int."""
            x, num = 0, 0
            # append symbol
            if string[0] not in '+-':
                string = '+' + string
            # parse string and calculate total num of x and sum of int    
            idx = 0
            while idx < len(string):
                curr = idx + 1
                while curr < len(string) and string[curr] not in '+-':
                    curr += 1
                value = string[idx:curr]
                idx = curr
                if value[-1] == 'x':
                    if len(value) == 2:
                        x += 1 if value[0] == '+' else -1
                    else:
                        x += int(value[:-1])
                else:
                    num += int(value)
            return x, num
    

Log in to reply
 

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