PR3_Skriptsprachen_GruppeD_SL1/s1_a51.py

25 lines
775 B
Python

class SparseMatrix:
def __init__(self):
self.__matrix = dict()
def save(self, matrix) -> None:
for row in range(len(matrix)):
for col in range(len(matrix[row])):
if matrix[row][col] != 0:
self.__matrix[(row, col)] = matrix[row][col]
def get(self, row, col) -> int or None:
if self.__matrix[(row, col)]:
return self.__matrix[(row, col)]
def __str__(self) -> str:
return '\n'.join(map(lambda pair: ': '.join(map(str, pair)), self.__matrix.items()))
if __name__ == "__main__":
# 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))