2022-11-08 14:28:42 +01:00
|
|
|
import collections
|
|
|
|
|
2022-11-05 15:33:32 +01:00
|
|
|
import numpy as np
|
|
|
|
from scipy import sparse
|
|
|
|
|
2022-11-08 14:28:42 +01:00
|
|
|
|
|
|
|
class Matrix:
|
|
|
|
def __init__(self):
|
|
|
|
self.matrix = collections.defaultdict(dict)
|
|
|
|
|
|
|
|
def set(self, col, ro, value):
|
|
|
|
if value == 0:
|
|
|
|
if self.matrix.get(col) and self.matrix.get(col).get(ro):
|
|
|
|
del self.matrix[col][ro]
|
|
|
|
else:
|
|
|
|
self.matrix[col][ro] = value
|
|
|
|
|
|
|
|
def get(self, col, ro):
|
|
|
|
if self.matrix.get(col) and self.matrix.get(col).get(row):
|
|
|
|
return self.matrix[col][row]
|
|
|
|
else:
|
|
|
|
return 0
|
|
|
|
|
|
|
|
|
2022-11-05 15:33:32 +01:00
|
|
|
if __name__ == "__main__":
|
|
|
|
# Aufgabe 1b
|
|
|
|
input_matrix = [[3, 0, -2, 11],
|
|
|
|
[0, 0, 9, 0],
|
|
|
|
[0, 7, 0, 0],
|
|
|
|
[0, 0, 0, 0]]
|
2022-11-08 14:28:42 +01:00
|
|
|
mar = Matrix()
|
2022-11-05 15:33:32 +01:00
|
|
|
for row in range(len(input_matrix)):
|
|
|
|
for column in range(len(input_matrix[0])):
|
2022-11-08 14:28:42 +01:00
|
|
|
mar.set(row, column, input_matrix[row][column])
|
2022-11-05 15:33:32 +01:00
|
|
|
|
2022-11-08 14:28:42 +01:00
|
|
|
print(mar.matrix)
|
2022-11-05 15:33:32 +01:00
|
|
|
# Aufgabe 1c
|
2022-11-08 14:28:42 +01:00
|
|
|
# print("\nThe sparce matrix computed without numpy\n" + str(sparse_matrix))
|
2022-11-05 15:33:32 +01:00
|
|
|
|
|
|
|
# faster way with numpy
|
|
|
|
input_matrix = np.array(input_matrix)
|
|
|
|
rows, columns = input_matrix.shape
|
|
|
|
sparse_matrix = sparse.csr_matrix(input_matrix)
|
|
|
|
print("\nThe sparce matrix computed with numpy\n" + str(sparse_matrix))
|