forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Sparse_matrix_Operation.py
115 lines (73 loc) · 1.97 KB
/
Sparse_matrix_Operation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
"""
Input:
Enter the number of rows: 3
Enter the number of columns: 3
Enter the entries row wise:
1
1
0
0
0
0
0
2
0
Output:
Given matrix is a sparse matrix
[0, 0, 2]
[0, 1, 1]
[1, 1, 2]
Time Complexity:O(noOfRows*noOfcolumns)
Space Complexity:O(1)
"""
# for row and column input
ROW = int(input("Enter the number of rows:"))
COLUMN = int(input("Enter the number of columns:"))
# Initialize matrix
matrix = []
print("Enter the entries row wise:")
# For user input
for i in range(ROW): # A for loop for row entries
a = []
for j in range(COLUMN): # A for loop for column entries
a.append(int(input()))
matrix.append(a) # taking input of arrays
# Initializing count = 0 to count the number of zeros.
count = 0
# Calculates number of rows and columns present in given matrix
matrix_rows = len(matrix)
matrix_cols = len(matrix[0])
# Calculates the size of the array
size = matrix_rows * matrix_cols
# Count all zero element present in matrix
for i in range(0, matrix_rows):
for j in range(0, matrix_cols):
if(matrix[i][j] == 0):
count = count + 1
# Sparse Matrix definition
def sparse_matrix():
size = 0
for i in range(ROW):
for j in range(COLUMN):
if (matrix[i][j] != 0):
size += 1
matrix_rows, matrix_cols = (3, size)
Print_Matrix = [[0 for i in range(matrix_cols)]
for j in range(matrix_rows)]
k = 0
for i in range(ROW):
for j in range(COLUMN):
if (matrix[i][j] != 0):
Print_Matrix[0][k] = i
Print_Matrix[1][k] = j
Print_Matrix[2][k] = matrix[i][j]
k += 1
for i in Print_Matrix:
print(i)
if(count == size):
print("Null Mtrix")
elif(count > (size/2)):
print("Given matrix is a sparse matrix")
sparse_matrix()
else:
print("Given matrix is not a sparse matrix")