Home > Software design >  How to compare 2 two-dimensional lists in python according to a given condition?
How to compare 2 two-dimensional lists in python according to a given condition?

Time:05-07

This function compares 2 matrices element by element, compares according to the principle that the corresponding elements should have the same parity

def equals(matr1, matr2):
    if len(matr1) != len(matr2):
        return False
    for index1 in range(len(matr1)):
        if len(matr1[index1]) != len(matr2[index1]):
            return False
        for index2 in range(len(matr1[index1])):
            if matr1[index1][index2] % 2 != matr2[index1][index2] % 2:
                return False
    return True
matrix [[1, 2], [3, 4]] # - satisfies the condition
matrix [[4, 6], [4, 5]] # - does not satisfy the condition

how to write this function in one line?

CodePudding user response:

One arguably dirty way to go would be to "map" the matrices to their remainders mod 2 using list comprehensions, then comparing the matrices:

equals = lambda mat1, mat2: [[e1 % 2 for e1 in l1] for l1 in mat1] == [[e2 % 2 for e2 in l2] for l2 in mat2]

you could deduplicate this using a function, cleaning it up a bit:

def matrix_mod(mat, mod):
    return [[e1 % mod for e1 in l1] for l1 in mat]
def equals(mat1, mat2):
    return matrix_mod(mat1, 2) == matrix_mod(mat2, 2)

  • Related