# How to solve a system of linear equations in Python with an iterative method?

## Question:

I have a system of linear equations represented as strings in Python, and I need to find integer values (positive or negative) for each of the variables that satisfy all equations simultaneously without contradictions. The number of variables and equations can vary, so the solution should adapt accordingly.

Here’s an example of such a system of equations:

``````from sympy import symbols, Eq, solve
import re

system_equations = [
'5 = X0 + Y0',
'6 = X0 + Y1',
'5 = X0 + Y3',
'5 = X0 + Y4',
'3 = X1 + Y2',
'0 = X2 + Y2',
'1 = X2 + Y4'
]

# Extract all variable names from the system of equations
variable_names = list(set(re.findall(r'[XY]d+', ' '.join(system_equations))))

# Create symbols for the variables
variables = symbols(' '.join(variable_names))
``````

It is important to keep in mind that the program must adapt to the number of variables (Xi and Yj) or/and equations that there are, this is just an example, where we have 8 unknowns and 7 linear equations.

For this example, one of the possible solutions where there are integer values that satisfy all the equations simultaneously (without contradictions), could be:

``````# a (posible) correct output
values_of_int_decomposition_variables = [['X0', 2], ['X1', 1], ['X2', -2], ['Y0', 3], ['Y1', 4], ['Y2', 2], ['Y3', 3], ['Y4', 3]]
``````

Note that if they manage to satisfy all the equations:

``````ij_number_to_decompose = Xi + Yj

5 = 2 + 3
6 = 2 + 4
5 = 2 + 3
5 = 2 + 3
3 = 1 + 2
0 = 2 + (-2)
1 = -2 + 3
``````

In the case of equations with the value of 0 it must necessarily be decomposed into 2 values equal in magnitude but of opposite sign (X2 and Y2 should have opposite values)

You can use PuLP or SciPY libraries for solving Linear Equations.

``````from sympy import symbols, Eq, solve
import re
from pulp import LpMaximize, LpProblem, LpVariable, value

system_equations = [
'5 = X0 + Y0',
'6 = X0 + Y1',
'5 = X0 + Y3',
'5 = X0 + Y4',
'3 = X1 + Y2',
'0 = X2 + Y2',
'1 = X2 + Y4'
]

variable_names = list(set(re.findall(r'[XY]d+', ' '.join(system_equations))))

variables = {var: LpVariable(var, lowBound=None, cat='Integer') for var in variable_names}

prob = LpProblem("IntegerLinearProgramming", LpMaximize)
print(variables)
for equation in system_equations:
lhs, rhs = equation.split('=')
lhs = lhs.strip()
rhs = rhs.strip()
print(rhs)
terms = re.findall(r'([+-]?s*d*s**?s*[XY]d+)', rhs)
constraint = sum(eval(term, {}, variables) for term in terms) == int(lhs)
prob += constraint

prob.solve()

values_of_int_decomposition_variables = [[var, int(value(variables[var]))] for var in variable_names]

print(values_of_int_decomposition_variables)
``````
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.