0% found this document useful (0 votes)
2 views1 page

Python Sparse Matrix Programs

The document provides Python programs for handling sparse matrices, including converting a sparse matrix to a 3-tuple representation, reconstructing the original matrix from this representation, and finding the transpose of the sparse representation. It includes code snippets and their corresponding outputs for each operation. The examples illustrate the transformation of a sparse matrix into a compact format and back, as well as the transposition process.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views1 page

Python Sparse Matrix Programs

The document provides Python programs for handling sparse matrices, including converting a sparse matrix to a 3-tuple representation, reconstructing the original matrix from this representation, and finding the transpose of the sparse representation. It includes code snippets and their corresponding outputs for each operation. The examples illustrate the transformation of a sparse matrix into a compact format and back, as well as the transposition process.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Programs: Sparse Matrix

1. Sparse Matrix to 3-Tuple Representation


matrix=[[0,0,3],[4,0,0],[0,5,0]]
rows=len(matrix); cols=len(matrix[0])
s=[]
for i in range(rows):
for j in range(cols):
if matrix[i][j]!=0:
[Link]([i,j,matrix[i][j]])
print("Original Matrix:")
for r in matrix: print(r)
print("Sparse Representation:")
print([rows,cols,len(s)])
for x in s: print(x)

Output:
Original Matrix:
[0, 0, 3]
[4, 0, 0]
[0, 5, 0]
Sparse Representation:
[3, 3, 3]
[0, 2, 3]
[1, 0, 4]
[2, 1, 5]

2. Sparse Representation to Matrix


s=[[3,3,3],[0,2,3],[1,0,4],[2,1,5]]
rows,cols,n=s[0]
m=[[0]*cols for _ in range(rows)]
for i in range(1,len(s)):
r,c,v=s[i]
m[r][c]=v
print("Matrix:")
for x in m: print(x)

Output:
[0, 0, 3]
[4, 0, 0]
[0, 5, 0]

3. Transpose of Sparse Representation


s=[[3,3,3],[0,2,3],[1,0,4],[2,1,5]]
t=[[s[0][1],s[0][0],s[0][2]]]
for i in range(1,len(s)):
r,c,v=s[i]
[Link]([c,r,v])
t[1:]=sorted(t[1:])
print("Transpose Sparse:")
for x in t: print(x)

Output:
[3, 3, 3]
[0, 1, 4]
[1, 2, 5]
[2, 0, 3]

You might also like