Change Aufgabe 4:

umbau auf klasse
main
Alexander Obwandner 2022-11-08 14:28:42 +01:00
parent fecf7c747f
commit 32e95c68f7
1 changed files with 25 additions and 7 deletions

View File

@ -1,23 +1,41 @@
import collections
import numpy as np import numpy as np
from scipy import sparse 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__": if __name__ == "__main__":
# Aufgabe 1b # Aufgabe 1b
input_matrix = [[3, 0, -2, 11], input_matrix = [[3, 0, -2, 11],
[0, 0, 9, 0], [0, 0, 9, 0],
[0, 7, 0, 0], [0, 7, 0, 0],
[0, 0, 0, 0]] [0, 0, 0, 0]]
sparse_matrix = [] mar = Matrix()
for row in range(len(input_matrix)): for row in range(len(input_matrix)):
for column in range(len(input_matrix[0])): for column in range(len(input_matrix[0])):
if input_matrix[row][column] != 0: mar.set(row, column, input_matrix[row][column])
# 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)
print(mar.matrix)
# Aufgabe 1c # 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 # faster way with numpy
input_matrix = np.array(input_matrix) input_matrix = np.array(input_matrix)