Click here to Skip to main content
15,868,051 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, I create matrix "adjacency_matrix" with following code:

Python
n = int(input()) # Initialize matrix

adjacency_matrix = []

# For user input

for i in range(n):

a =[]

for j in range(n):

a.append(int(input()))

adjacency_matrix.append(a)


I want to save indices of non zero elements of above matrix.

for example n = 3;

Python
adjacency_matrix =

2 3 0

0 0 1

1 5 0


I want to save rows of non zero element in "li_r":

Python
li_r = [0 0 1 2 2]


I want to save columns of non zero element in "li_c":

Python
li_c = [0 1 2 0 1]



My Question is: Is this code is true?

Python
for i in range(n):

li_r = [];

li_c = []

for j in range(n):

if adjacency_matrix[i-1][j-1]!=0:

li_r.append(i-1)

li_c.append(j-1)


What I have tried:

I write that code, by it's not work.
Posted
Updated 15-Jun-22 20:30pm

1 solution

Try the following code
Python
n=3
adjacency_matrix =[ [2, 3, 0] , [0, 0, 1] , [1, 5, 0] ]

li_r = []
li_c = []
for i in range(n):
  for j in range(n):
    if adjacency_matrix[i][j]!=0:
      li_r.append(i)
      li_c.append(j)

print(li_r)
print(li_c)


You may also use the more concise, but less efficient
Python
n=3
adjacency_matrix =[ [2, 3, 0] , [0, 0, 1] , [1, 5, 0] ]

li_r = [r for r in range(n) for c in range(n) if adjacency_matrix[r][c] != 0]
li_c = [c for r in range(n) for c in range(n) if adjacency_matrix[r][c] != 0]

print(li_r)
print(li_c)
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900