Advertisements
I got a fairly large array of arrays of length 2 (List[List[int, int]])
How can I unique arrays of them? Preferably without using different libraries
I’ve seen several solutions that use numpy, but I’m unlikely to be able to use this in olympiads
# Example input:
nums = [[2, 9], [3, 6], [9, 2], [6, 3]]
for i in nums:
# some code here
# Output:
# nums = [[2, 9], [3, 6]]
I tried doing this but I guess it’s not a very fast solution
# Example input:
nums = [[2, 9], [3, 6], [9, 2], [6, 3]]
unique = []
for i in nums:
if sorted(i) not in unique:
unique.append(sorted(i))
# Output:
print(unique) # [[2, 9], [3, 6]]
>Solution :
To deal with sets not being hashable, you can create a set of frozensets this way:
unique = {frozenset(i) for i in nums}
Then you can use whichever means to turn the results into the objects you want; for example:
unique = [list(i) for i in unique]