| 1 |
from __future__ import division |
| 2 |
|
| 3 |
EPSILON = 1E-12 |
| 4 |
|
| 5 |
|
| 6 |
class SparseMatrix: |
| 7 |
|
| 8 |
def __init__(self, height): |
| 9 |
self.lines = [{} for row in range(height)] |
| 10 |
|
| 11 |
def __getitem__(self, (row, col)): |
| 12 |
return self.lines[row].get(col, 0) |
| 13 |
|
| 14 |
def __setitem__(self, (row, col), value): |
| 15 |
if abs(value) > EPSILON: |
| 16 |
self.lines[row][col] = value |
| 17 |
else: |
| 18 |
try: |
| 19 |
del self.lines[row][col] |
| 20 |
except KeyError: |
| 21 |
pass |
| 22 |
|
| 23 |
def copy(self): |
| 24 |
m = SparseMatrix(len(self.lines)) |
| 25 |
for line1, line2 in zip(self.lines, m.lines): |
| 26 |
line2.update(line1) |
| 27 |
return m |
| 28 |
|
| 29 |
def solve(self, vector): |
| 30 |
"""Solves 'self * [x1...xn] == vector'; returns the list [x1...xn]. |
| 31 |
Raises ValueError if no solution or indeterminate. |
| 32 |
""" |
| 33 |
vector = list(vector) |
| 34 |
lines = [line.copy() for line in self.lines] |
| 35 |
columns = [{} for i in range(len(vector))] |
| 36 |
for i, line in enumerate(lines): |
| 37 |
for j, a in line.items(): |
| 38 |
columns[j][i] = a |
| 39 |
lines_left = dict.fromkeys(range(len(self.lines))) |
| 40 |
nrows = [] |
| 41 |
for ncol in range(len(vector)): |
| 42 |
currentcolumn = columns[ncol] |
| 43 |
lst = [(abs(a), i) for (i, a) in currentcolumn.items() |
| 44 |
if i in lines_left] |
| 45 |
_, nrow = max(lst) |
| 46 |
nrows.append(nrow) |
| 47 |
del lines_left[nrow] |
| 48 |
line1 = lines[nrow] |
| 49 |
maxa = line1[ncol] |
| 50 |
for _, i in lst: |
| 51 |
if i != nrow: |
| 52 |
line2 = lines[i] |
| 53 |
a = line2.pop(ncol) |
| 54 |
|
| 55 |
factor = a / maxa |
| 56 |
vector[i] -= factor*vector[nrow] |
| 57 |
for col in line1: |
| 58 |
if col > ncol: |
| 59 |
value = line2.get(col, 0) - factor*line1[col] |
| 60 |
if abs(value) > EPSILON: |
| 61 |
line2[col] = columns[col][i] = value |
| 62 |
else: |
| 63 |
line2.pop(col, 0) |
| 64 |
columns[col].pop(i, 0) |
| 65 |
solution = [None] * len(vector) |
| 66 |
for i in range(len(vector)-1, -1, -1): |
| 67 |
row = nrows[i] |
| 68 |
line = lines[row] |
| 69 |
total = vector[row] |
| 70 |
for j, a in line.items(): |
| 71 |
if j != i: |
| 72 |
total -= a * solution[j] |
| 73 |
solution[i] = total / line[i] |
| 74 |
return solution |