parent
fecf7c747f
commit
32e95c68f7
32
s1_a51.py
32
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)
|
||||
|
|
Loading…
Reference in New Issue