Search code examples
pythonloopsmatrixcycle

How to iterate through a matrix column in python


I have a matrix with the cell values only 0 or 1.

I want to count how many ones or zeros are there in the same row or column to a given cell.

For example, the value matrix[r][c] is 1, so I want to know how many ones are there in the same row. This code does that:

count_in_row = 0
value = matrix[r][c]
for i in matrix[r]:
    if i == value:
        count_in_row += 1

The for cycle iterates through the same row and counts all ones (cells with the same value).

What if I want to do the same process with columns? Will I iterate through the whole matrix or it is possible through just one column?

PS: I don't want to use numpy, transpose or zip; better with composite cycle.


Solution

  • You have not specified what the datatype of your matrix is. If it is a list of lists, then there is no way to "get just one column", but the code still is similar (assuming that r and c are of type int):

    I added the functionality to only count the cells adjacent to the cell in question (above, below, left and right; does NOT consider diagonals); this is done checking that the difference between indexes is not greater than 1.

    count_in_row = 0
    count_in_col = 0
    value = matrix[r][c]
    
    for j in range(len(matrix[r])):
        if abs(j - c) <= 1:             # only if it is adjacent
            if matrix[r][j] == value:
                count_in_row += 1
    for i in range(len(matrix)):
        if abs(i - r) <= 1:             # only if it is adjacent
            if matrix[i][c] == value:
                count_in_col += 1
    

    Or if following the way you started it (whole rows and columns, not only adjacent ones):

    for col_val in matrix[r]:
        if col_val == value:
            count_in_row += 1
    for row in matrix:
        if row[c] == value:
            count_in_col += 1
    

    If you will be doind this for a lot of cells, then there are better ways to do that (even without numpy, but numpy is defenitively a very good option).