import collections import numpy as np from scipy import sparse class Matrix: def __init__(self): self.__matrix = collections.defaultdict(dict) def set(self, column, row, value): if value == 0: if self.__matrix.get(column) and self.__matrix.get(column).get(row): del self.__matrix[column][row] else: self.__matrix[column][row] = value def get(self, column, row): if self.__matrix.get(column) and self.__matrix.get(column).get(row): return self.__matrix[column][row] else: return 0 def print(self): print(self.__matrix) if __name__ == "__main__": # Aufgabe 1b input_matrix = [[3, 0, -2, 11], [0, 0, 9, 0], [0, 7, 0, 0], [0, 0, 0, 0]] 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]) sparse_matrix.print() # Aufgabe 1c # print("\nThe sparce matrix computed without numpy\n" + str(sparse_matrix)) # 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))