PR3_Skriptsprachen_GruppeD_SL1/s1_a51.py

57 lines
1.6 KiB
Python
Raw Normal View History

2022-11-08 14:28:42 +01:00
import collections
2022-11-05 15:33:32 +01:00
import numpy as np
from scipy import sparse
2022-11-08 14:28:42 +01:00
class Matrix:
def __init__(self):
2022-11-08 16:11:58 +01:00
self.__matrix = collections.defaultdict(dict)
2022-11-08 14:28:42 +01:00
def set(self, row, column, value):
if value != 0:
self.__matrix[row][column] = value
2022-11-08 14:28:42 +01:00
else:
if self.__matrix.get(row) and self.__matrix.get(row).get(column):
del self.__matrix[row][column]
2022-11-08 14:28:42 +01:00
def get(self, row, column):
if self.__matrix.get(row) and self.__matrix.get(row).get(column):
return self.__matrix[row][column]
2022-11-08 14:28:42 +01:00
else:
return 0
2022-11-08 16:11:58 +01:00
def print(self):
print(self.__matrix)
2022-11-08 14:28:42 +01:00
2022-11-05 15:33:32 +01:00
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])
2022-11-05 15:33:32 +01:00
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()
2022-11-05 15:33:32 +01:00
# 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))