< !- START disable copy paste -->

Saturday, 3 March 2018

Sparse Matrix Using List

This is sparse matrix program. A matrix in which number of zeros are greater than half the size of matrix is known as sparse matrix.

Source Code:

row=int(input("enter number of rows : "))
col=int(input("enter number of coloumns : "))

X = [[0]*col for j in range(row)]
count=0

print ("entry elements")
for i in range (row):
  for j in range (col): 
    X[i][j] = int(input())

print("matrix is:")
for i in range(row):
    for j in range(col):
        print(X[i][j], end=' ')
    print()

for i in range(row):
    for j in range(col):
        if X[i][j]==0:
            count=count+1

print("number of zeros:",count)

if count>(row*col)//2:
    print("sparse matrix")
else:

    print("not sparse matrix")

Output:

Python 3.4.0 (v3.4.0:04f714765c13, Mar 16 2014, 19:24:06) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
enter number of rows : 3
enter number of coloumns : 3
entry elements
1
2
3
0
0
0
4
5
6
matrix is:
1 2 3 
0 0 0 
4 5 6 
number of zeros: 3
not sparse matrix
>>> ================================ RESTART ================================
>>> 
enter number of rows : 3
enter number of coloumns : 3
entry elements
1
2
3
0
0
0
0
4
5
matrix is:
1 2 3 
0 0 0 
0 4 5 
number of zeros: 4
not sparse matrix
>>> ================================ RESTART ================================
>>> 
enter number of rows : 3
enter number of coloumns : 3
entry elements
1
2
3
0
0
0
0
0
4
matrix is:
1 2 3 
0 0 0 
0 0 4 
number of zeros: 5
sparse matrix
>>>

Now my new Blog on Fundamentals of Python can be found at https://fundamentalsofpython.blogspot.com/2020/02/list-manipulations.html

No comments:

Post a Comment

Reverse Doubly Linked List

Source Code class Node:    def __init__(self,data):         self.data = data         self.left = None         self.right = None cla...