PR3_Skriptsprachen_GruppeD_SL1/s1_a51.py

25 lines
762 B
Python
Raw Permalink Normal View History

2023-03-30 01:29:11 +02:00
class SparseMatrix:
2022-11-08 14:28:42 +01:00
def __init__(self):
2023-03-30 01:29:11 +02:00
self.__matrix = dict()
2022-11-08 14:28:42 +01:00
2023-03-30 01:29:11 +02:00
def save(self, matrix) -> None:
2023-04-01 02:30:56 +02:00
for row, values in enumerate(matrix):
for col, value in enumerate(values):
if value != 0:
self.__matrix[(row, col)] = value
2022-11-08 14:28:42 +01:00
2023-03-30 01:29:11 +02:00
def get(self, row, col) -> int or None:
if self.__matrix[(row, col)]:
return self.__matrix[(row, col)]
2022-11-08 14:28:42 +01:00
2023-03-30 01:29:11 +02:00
def __str__(self) -> str:
2023-04-01 02:30:56 +02:00
return '\n'.join(map(lambda pair: ' : '.join(map(str, pair)), self.__matrix.items()))
2022-11-08 16:11:58 +01:00
2022-11-08 14:28:42 +01:00
2022-11-05 15:33:32 +01:00
if __name__ == "__main__":
2023-03-30 01:29:11 +02:00
# 5.1
sparse_matrix = SparseMatrix()
sparse_matrix.save([[3, 0, -2, 11], [0, 0, 9, 0], [0, 7, 0, 0], [0, 0, 0, 0]])
print(sparse_matrix)
print(sparse_matrix.get(0, 0))