PR3_Skriptsprachen_GruppeD_SL1/s1_a51.py

27 lines
1002 B
Python

import numpy as np
from scipy import sparse
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 = []
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)
# 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))