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):
|
2022-11-08 16:11:58 +01:00
|
|
|
self.__matrix = collections.defaultdict(dict)
|
2022-11-08 14:28:42 +01:00
|
|
|
|
2022-11-08 16:11:58 +01:00
|
|
|
def set(self, column, row, value):
|
2022-11-08 14:28:42 +01:00
|
|
|
if value == 0:
|
2022-11-08 16:11:58 +01:00
|
|
|
if self.__matrix.get(column) and self.__matrix.get(column).get(row):
|
|
|
|
del self.__matrix[column][row]
|
2022-11-08 14:28:42 +01:00
|
|
|
else:
|
2022-11-08 16:11:58 +01:00
|
|
|
self.__matrix[column][row] = value
|
2022-11-08 14:28:42 +01:00
|
|
|
|
2022-11-08 16:11:58 +01:00
|
|
|
def get(self, column, row):
|
|
|
|
if self.__matrix.get(column) and self.__matrix.get(column).get(row):
|
|
|
|
return self.__matrix[column][row]
|
2022-11-08 14:28:42 +01:00
|
|
|
else:
|
|
|
|
return 0
|
|
|
|
|
2022-11-08 16:11:58 +01:00
|
|
|
def print(self):
|
|
|
|
print(self.__matrix)
|
|
|
|
|
2022-11-08 14:28:42 +01:00
|
|
|
|
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 16:11:58 +01:00
|
|
|
sparse_matrix = Matrix()
|
|
|
|
for column in range(len(input_matrix)):
|
|
|
|
for row in range(len(input_matrix[0])):
|
|
|
|
sparse_matrix.set(column, row, input_matrix[row][column])
|
2022-11-05 15:33:32 +01:00
|
|
|
|
2022-11-08 16:11:58 +01:00
|
|
|
sparse_matrix.print()
|
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))
|