1

I have a rectangular matrix with digits only, i want calculate the number of different unique 2 × 2 square matrices in it.

I stored all possible 2x2 matrices in a new list. Now I want to re move all duplicate matrices from this new list. I don't know how to do it. If I use 'set()' function it gives me the error "unhashable type: 'list' ".

def differentSquares(matrix):
    squares_list = []
    for i in range (len(matrix)-1):
        for j in range (len(matrix[i])-1):
            temp=[[matrix[i][j],matrix[i][j+1]],
                  [matrix[i+1][j],matrix[i+1][j+1]]]
            squares_list.append(temp)
    return len(squares_list)

I know this problem can be solved by a different logic but I still want to know how can someone remove a duplicate matrix from a list of matrices.

If I enter the following input

Matrix=[[1,2,1], 
        [2,2,2], 
        [2,2,2], 
        [1,2,3], 
        [2,2,1]]

The value returned is 8 as I returned the length of the list without removing the duplicates. If I remove the duplicates the answer will become 6(correct answer)

eyllanesc
  • 235,170
  • 19
  • 170
  • 241

2 Answers2

0

Lists are mutable(can be changed) and therefore cannot be hashed. Instead try to use tuples which are immutable and therefore can be hashed.

def differentSquares(matrix):
    squares_list = []
    for i in range(len(matrix) - 1):
        for j in range(len(matrix[i]) - 1):
            temp=((matrix[i][j],   matrix[i][j+1]),
                  (matrix[i+1][j], matrix[i+1][j+1]))
            squares_list.append(temp)
    return len(set(squares_list))
Alex
  • 963
  • 9
  • 11
0

As mentioned by Alex, you can hash only immutable type objects in a set. list is mutable whereas tuple is immutable.

For more info - Hashable, immutable

Also, you can directly add your immutable objects to a set. Since a set will always contain unique elements, the add operation will not add any duplicates.

def differentSquares(matrix):
    unique_squares = set() # Create a set for adding unique 2x2 matrices
    for i in range (len(matrix)-1):
        for j in range (len(matrix[i])-1):
            temp=((matrix[i][j],matrix[i][j+1]),
                (matrix[i+1][j],matrix[i+1][j+1]))
            unique_squares.add(temp) # Add the matrix. It will not add any duplicates
    return len(unique_squares) # Returns 6 for the given example
Ganesh Tata
  • 1,118
  • 8
  • 26