Solve the Linear Equation of Single Variable | def to solve the given equation ; Traverse the equation ; For cases such as : x , - x , + x ; Flip sign once ' = ' is seen ; There may be a number left in the end ; For infinite solutions ; For no solution ; x = total sum / coeff of x ' - ' sign indicates moving numeric value to right hand side ; Driver code
def solveEquation ( equation ) : NEW_LINE INDENT n = len ( equation ) NEW_LINE sign = 1 NEW_LINE coeff = 0 NEW_LINE total = 0 NEW_LINE i = 0 NEW_LINE for j in range ( 0 , n ) : NEW_LINE INDENT if ( equation [ j ] == ' + ' or equation [ j ] == ' - ' ) : NEW_LINE INDENT if ( j > i ) : NEW_LINE INDENT total = ( total + sign * int ( equation [ i : j ] ) ) NEW_LINE DEDENT i = j NEW_LINE DEDENT elif ( equation [ j ] == ' x ' ) : NEW_LINE INDENT if ( ( i == j ) or equation [ j - 1 ] == ' + ' ) : NEW_LINE INDENT coeff += sign NEW_LINE DEDENT elif ( equation [ j - 1 ] == ' - ' ) : NEW_LINE INDENT coeff = coeff - sign NEW_LINE DEDENT else : NEW_LINE INDENT coeff = ( coeff + sign * int ( equation [ i : j ] ) ) NEW_LINE DEDENT i = j + 1 NEW_LINE DEDENT elif ( equation [ j ] == ' = ' ) : NEW_LINE INDENT if ( j > i ) : NEW_LINE INDENT total = ( total + sign * int ( equation [ i : j ] ) ) NEW_LINE DEDENT sign = - 1 NEW_LINE i = j + 1 NEW_LINE DEDENT DEDENT if ( i < n ) : NEW_LINE INDENT total = ( total + sign * int ( equation [ i : len ( equation ) ] ) ) NEW_LINE DEDENT if ( coeff == 0 and total == 0 ) : NEW_LINE INDENT return " Infinite ▁ solutions " NEW_LINE DEDENT if ( coeff == 0 and total ) : NEW_LINE INDENT return " No ▁ solution " NEW_LINE DEDENT ans = - total / coeff NEW_LINE return int ( ans ) NEW_LINE DEDENT equation = " x + 5-3 + x = 6 + x - 2" NEW_LINE print ( " x ▁ = ▁ { } " . format ( solveEquation ( equation ) ) ) NEW_LINE