Home > Blockchain >  How to detect any duplicate in each row and column in 2d array in python
How to detect any duplicate in each row and column in 2d array in python

Time:09-19

I was given an assignment to check for duplicates. If there are duplicates then we have to return false else true. As I am new to python I am unable to write the code. So it will be helpful if you guys help me with it. For Example

    test = ([1,2,3,4],
    [2,3,1,4],
    [1,2,3,4])

should return false.

CodePudding user response:

You have to iterate through each element and perform two checks - the row and a column - if duplicate occurs return false. Hence the array is two-dimensional you will have to perform a nested loop:

    for row in array:
        for cell in row:
            if check(array[row][cell]):
                return false
    return true

The check() function have to test, if any other cell in the same column or row is the same. So simmilar iteration is to do. Remember not to check the cell with its own value. Details of implementation are great excercise, try to do it by your own.

CodePudding user response:

Here is a generic recipe.

  • iterate through the rows i.
  • then iterate through the items in the rows j.
  • blank list to house items x and check for duplicates.

This would work:

test = ([1,2,3,4],
    [2,3,1,4],
    [1,2,3,4])

def test_array(test):
    for i in test:
        x = []
        for j in i:
            if j in x:
                return False
            else:
                x.append(j)
    return True

test_array(test)

CodePudding user response:

no_duplicates below will do this. There's a helper that checks lists for duplicates. The helper is slow because set creation is slow, but for many uses this will be effective. Modifying the helper is probably the easiest way to speed this up, if necessary.

def list_no_duplicates(my_list):
    return len(my_list) == len(set(my_list))

def no_duplicates(arr):
    return all(list_no_duplicates(e) for e in arr)
  • Related