From 32e95c68f75d0e6f87ce8223e11cbebf4898ec00 Mon Sep 17 00:00:00 2001 From: alex <2121669@stud.hs-mannheim.de> Date: Tue, 8 Nov 2022 14:28:42 +0100 Subject: [PATCH] Change Aufgabe 4: umbau auf klasse --- s1_a51.py | 32 +++++++++++++++++++++++++------- 1 file changed, 25 insertions(+), 7 deletions(-) diff --git a/s1_a51.py b/s1_a51.py index 9b9bf30..1325cbe 100644 --- a/s1_a51.py +++ b/s1_a51.py @@ -1,23 +1,41 @@ +import collections + import numpy as np from scipy import sparse + +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 + + 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 = [] + mar = Matrix() for row in range(len(input_matrix)): for column in range(len(input_matrix[0])): - if input_matrix[row][column] != 0: - # Aufgabe 1d - print("Index: ["+str(row)+"]"+"["+str(column)+"] = "+str(input_matrix[row][column])) - triplet = [row, column, input_matrix[row][column]] # saving index of not null values - sparse_matrix.append(triplet) + mar.set(row, column, input_matrix[row][column]) + print(mar.matrix) # Aufgabe 1c - print("\nThe sparce matrix computed without numpy\n" + str(sparse_matrix)) + # print("\nThe sparce matrix computed without numpy\n" + str(sparse_matrix)) # faster way with numpy input_matrix = np.array(input_matrix)