Home > Software design >  Given matrix we need to keep only columns of matrix that have odd and even elements
Given matrix we need to keep only columns of matrix that have odd and even elements

Time:04-04

Given matrix we need to keep only those columns of matrix that have odd and even elements.

def all_even(row):
    count = 0
    for i in row:
        if i % 2==0:
            count =1
    if count == len(row):
        return True
def all_odd(row):
    count = 0
    for i in row:
        if i % 2 != 0:
            count =1
    if count == len(row):
        return True



def del_column(mat, i):
    for row in mat:
        del row[i]
    return mat
def column_m(matrix,i):
    return [row[i] for row in matrix]

def check(matrix):
    columns = len(matrix[0])
    for i in range(columns):

        if all_even(column_m(matrix,i)) or all_odd(column_m(matrix,i)):
            matrix = del_column(matrix,i)
    return matrix



print(check([[1,2,3,4],
             [4,5,3,4],
             [7,8,3,4]]))

This is my code which gives error in this example because list index is out of range.

Can you help how solve this problem? Without using numpy,pandas or additional libraries.

CodePudding user response:

here :

def del_column(mat, i):
    for row in mat:
        del row[i]
    return mat

You delete an index (meaning the size of your list decreases), then go further in the list index. If there is one deleted element or more, you will try to access indexes that don't exist anymore.

You can replace it with a while statement :

i = 0
while i < len(matrix[0]):
    if all_even(column_m(matrix,i)) or all_odd(column_m(matrix,i)):
        matrix = del_column(matrix,i)
    else:
        i  = 1
return matrix

This will it

CodePudding user response:

So when you delete a column from the matrix, the matrix gets shorter causing the error. Say, after deleting the [3,3,3], the matrix becomes [[1, 2, 4], [4, 5, 4], [7, 8, 4]] so index 3 is out of range. You can solve this by using a while loop. This can be done by replacing:

def check(matrix):
    columns = len(matrix[0])
    for i in range(columns):

        if all_even(column_m(matrix,i)) or all_odd(column_m(matrix,i)):
            matrix = del_column(matrix,i)
    return matrix

With:

def check(matrix):
    columns = len(matrix[0])
    i = 0
    while i < columns:
        print(i)
        if all_even(column_m(matrix,i)) or all_odd(column_m(matrix,i)):
            matrix = del_column(matrix,i)
            columns -= 1 # Revert loop by one iteration and reduce the iteration 
            i-=1         # size
        i =1
    return matrix

while loop is used because the number of iterations is decided at the beginning in a for loop. And we need to revert it back by one iteration to help decrease the highest value of the index

  • Related