How to print the cordinates of matrix whose corresponding row and columns are zero in python?

I need print the coordinates of matrix whose corresponding row and columns are only zeros

Example:

3 3
1 0 0
0 0 0
1 0 0

in above example at coordinate (1,1) rows and cols are zero(0) like that I need to print all coronates having row and col as zero.(like need to check in plus shape)

My code:

r,c=map(int,input().split())
l=[list(map(int,input().split())) for i in range(r)]
for i in range(len(l)):
    for j in range(0,len(l[i])):
        if sum(l[i])==0 and sum(l[j])==0:
          print(i,j)

my code is working for above mentioned input but for bellow mention input not working why??

input:

6 13 

1 0 1 0 1 0 1 0 1 0 1 0 0     
0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 0 0 
0 1 0 1 0 1 0 1 0 1 0 1 0

output needed:

1 13
2 13
3 13
4 13

my output:

1 1
1 2
1 3
1 4

Traceback (most recent call last):
  File "main.py", line 5, in <module>
    if sum(l[i])==0 and sum(l[j])==0:
IndexError: list index out of range

What mistake i made? Please help me!!

>Solution :

Based on how you are iterating over the table, l[i] will indeed give you the ith row of l, but l[j] will give you the jth row of table l, whereas you are actually wanting the jth column of l.

The index error occurs b/c you have more columns than rows, and so you eventually attempt to access the 7th row (rather than column) which indeed does not exist

Not the most efficient way to do this but to get the jth column you could iterate over each l[x][j] for each row x: sum(l[x][j] for x in range(len(l))])

To wit:

r,c=map(int,input().split())
l=[list(map(int,input().split())) for i in range(r)]
for i in range(len(l)):
    for j in range(0,len(l[i])):
        if sum(l[i])==0 and sum(l[x][j] for x in range(len(l)))==0:
          print(i,j)


# Outputs:
1 12
2 12
3 12
4 12

On the test case above

Leave a Reply