PR3_Skriptsprachen_GruppeD_SL1/s1_a51.py

45 lines
1.2 KiB
Python

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]]
mar = Matrix()
for row in range(len(input_matrix)):
for column in range(len(input_matrix[0])):
mar.set(row, column, input_matrix[row][column])
print(mar.matrix)
# 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))