Home > Net >  Counting null rows and columns in a n*n matrix
Counting null rows and columns in a n*n matrix

Time:01-26

I'm trying to solve the following problem:

Write the function null(A) which, given a matrix of integers A (list of lists), of size n * n, counts the number of null rows and columns (that is, with all elements equal to zero). The result should be a list with 2 elements: number of null rows and number of null columns.

Could anyone suggest a solution please? I've been blocked in this question for a while, it is probably very easy but I can't seem to solve it.

I'm in an introductory Python class, so the solution should be simple (no packages needed). Thank you so much in advance!

CodePudding user response:

I would suggest that you get familiar with "for x in y" code, to see how it works.

For example, if you have a list, you can access every item of the list:

example_list = ['a', 4, 'g']

for x in example_list:
    print(x)

Output:

a
4
g

instead of x, you can type anything, it doesn't matter, but whatever you write there, will be a local variable containing the value of every item in the list, one at a time (so, if you write "for item in example_list", be sure to print(item))

In the case of a 2d_list, every item will be a list itself, so...

2d_example_list = [[1, 2, 3], ['a', 'b', 'c'], ['Never', 'Gonna', 'Give', 'You', 'Up']]

for item in 2d_example_list:
    print(item)

Output:

[1, 2, 3]
['a', 'b', 'c']
['Never', 'Gonna', 'Give', 'You', 'Up']

You can also nest two "for" loops to access every item of every list.

I think this is enough for you to be able to find the answer to your problem, good luck! :)

CodePudding user response:

You may enter a matrix of your choice. The null() function traverses each row and checks if the maximum value of the row is 0 - if it's true, means all values are 0. Then, it transposes the matrix and follows the same convention to check each column. Increments values when finds a null column or row.

import numpy as np

def null(array):
    rowCounter = 0
    columnCounter = 0
    for row in array:
        if (max(row) == 0):
            rowCounter  = 1
    
    array = array.transpose()
    for row in array:
        if (max(row) == 0):
            columnCounter  = 1
            
    return rowCounter, columnCounter
            

array = np.array([[0,0,0,0], [1,1,1,0], [2,2,2,0], [0,0,0,0]])

print(array)

print("Number of null rows and columns:"   str(null(array)))
  • Related