MCPcopy Index your code
hub / github.com/TheAlgorithms/Python / simplify

Function simplify

maths/simultaneous_linear_equation_solver.py:12–54  ·  view source on GitHub ↗

>>> simplify([[1, 2, 3], [4, 5, 6]]) [[1.0, 2.0, 3.0], [0.0, 0.75, 1.5]] >>> simplify([[5, 2, 5], [5, 1, 10]]) [[1.0, 0.4, 1.0], [0.0, 0.2, -1.0]]

(current_set: list[list])

Source from the content-addressed store, hash-verified

10
11
12def simplify(current_set: list[list]) -> list[list]:
13 """
14 >>> simplify([[1, 2, 3], [4, 5, 6]])
15 [[1.0, 2.0, 3.0], [0.0, 0.75, 1.5]]
16 >>> simplify([[5, 2, 5], [5, 1, 10]])
17 [[1.0, 0.4, 1.0], [0.0, 0.2, -1.0]]
18 """
19 # Divide each row by magnitude of first term --> creates 'unit' matrix
20 duplicate_set = current_set.copy()
21 for row_index, row in enumerate(duplicate_set):
22 magnitude = row[0]
23 for column_index, column in enumerate(row):
24 if magnitude == 0:
25 current_set[row_index][column_index] = column
26 continue
27 current_set[row_index][column_index] = column / magnitude
28 # Subtract to cancel term
29 first_row = current_set[0]
30 final_set = [first_row]
31 current_set = current_set[1::]
32 for row in current_set:
33 temp_row = []
34 # If first term is 0, it is already in form we want, so we preserve it
35 if row[0] == 0:
36 final_set.append(row)
37 continue
38 for column_index in range(len(row)):
39 temp_row.append(first_row[column_index] - row[column_index])
40 final_set.append(temp_row)
41 # Create next recursion iteration set
42 if len(final_set[0]) != 3:
43 current_first_row = final_set[0]
44 current_first_column = []
45 next_iteration = []
46 for row in final_set[1::]:
47 current_first_column.append(row[0])
48 next_iteration.append(row[1::])
49 resultant = simplify(next_iteration)
50 for i in range(len(resultant)):
51 resultant[i].insert(0, current_first_column[i])
52 resultant.insert(0, current_first_row)
53 final_set = resultant
54 return final_set
55
56
57def solve_simultaneous(equations: list[list]) -> list:

Callers 1

solve_simultaneousFunction · 0.85

Calls 3

copyMethod · 0.80
appendMethod · 0.45
insertMethod · 0.45

Tested by

no test coverage detected