Skip to content

Latest commit

 

History

History
61 lines (47 loc) · 1.73 KB

640.md

File metadata and controls

61 lines (47 loc) · 1.73 KB

640 Solve the Equation

Description

link


Solution

  • See Code

Code

class Solution:
    def solveEquation(self, equation: str) -> str:
        # Equation is represented by list of tuples;
        # Each element in the list is (expression, sign) ;; sign is True for positive, False for negative
        
        # Eliminate '=' first to separate right hand side and left hand side
        [left, right] = equation.split('=')
        
        # Eliminate '+' next; carry over sign
        eq, next_eq = [(left, True), (right, False)], []
        for (term , sign) in eq:
            splits = term.split('+')
            for split in splits:
                next_eq.append((split, sign))
                
        # Eliminate '-' next; carry over sign ; Pay special attention to negative numbers
        eq, next_eq = next_eq, []
        for (term , sign) in eq:
            splits = term.split('-')
            if term[0] != '-':
                next_eq.append((splits[0], sign))
            for split in splits[1:]:
                next_eq.append((split, not sign))
        
        # Get the equation in the form of ax + b = 0; i.e compute a and b
        # note that 'x' = 1x 
        eq = next_eq
        a = b = 0
        for (term,sign) in eq:
            if term[-1] == 'x':
                num_term = term[:-1]
                num = int(num_term) if num_term != '' else 1
                a += num if sign else (-num)
            else:
                num = int(term)
                b += num if sign else (-num)
        
        if a == 0:
            return "Infinite solutions" if b == 0 else "No solution"
        else:
            return "x="+str(-b//a)