Reputation: 65
I am trying to read a file and check to see that every number is present, all unique. I tried checking the equality of the length of the list and the length of the set. I get this error TypeError: unhashable type: 'list' Do i have to convert the list to something else?
Here is code
def readMatrix(filNam):
matrixList = []
numFile = open(filNam, "r")
lines = numFile.readlines()
for line in lines:
line = line.split()
row = []
for i in line:
row.append(int(i))
matrixList.append(row)
return matrixList
def eachNumPresent(matrix):
if len(matrix) == len(set(matrix)):
return True
else:
return False
Upvotes: 0
Views: 65
Reputation: 8709
"set" doesn't work on list of lists but works fine on list of tuples. So use the below code :
matrixList.append(tuple(row))
instead of :
matrixList.append(row)
Upvotes: 0
Reputation: 40904
Your matrix
is a list of lists. When you write set(matrix)
, Python tries to create a set of all rows of the matrix. Your rows are lists, which are mutable and unhashable.
What you want is a set of all values in the matrix. You can count it with an explicit loop:
all_values = set()
for row in matrix:
all_values.update(row)
# here all_values contains all distinct values form matrix
You could also write a nested list comprehension:
all_values = set(x for row in matrix for x in row)
Upvotes: 1
Reputation: 571
A list cannot be an element of a set, so you cannot pass a list of lists to set(). You need to unravel the list of lists to a single list, then pass to set (so integers are your set elements).
unraveled = [x for line in matrix for x in line]
return len(unraveled) == len(set(unraveled))
Upvotes: 2