import collections import numpy as np from scipy import sparse class Matrix: def __init__(self): self.__matrix = collections.defaultdict(dict) def set(self, row, column, value): if value != 0: self.__matrix[row][column] = value else: if self.__matrix.get(row) and self.__matrix.get(row).get(column): del self.__matrix[row][column] def get(self, row, column): if self.__matrix.get(row) and self.__matrix.get(row).get(column): return self.__matrix[row][column] 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 row in range(len(input_matrix)): # for column in range(len(input_matrix[0])): # sparse_matrix.set(row, column, input_matrix[row][column]) sparce_matrix = {} rows = len(input_matrix) columns = len(input_matrix[0]) for row in range(rows): for column in range(columns): if input_matrix[row][column] != 0: sparce_matrix[(row, column)] = input_matrix[row][column] # Aufgabe 1c print("\n The sparce matrix without numpy\n" + str(sparce_matrix)) # sparse_matrix.print() # 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))