I'm trying to compare two lists in Python, checking if they are the same. The problem is that both lists can contain duplicate elements, and in order to be considered equal, they need to have the same amount of duplicate elements.
I've currently "solved" this by creating a copy of both lists, and removing an element from both lists if they are equal:
def equals(v1: Vertex, v2: Vertex) -> bool:
# also checks if neighbourhoods are the same size
if v1.label == v2.label:
# copy the neighbourhoods to prevent data loss on removal of checked vertices
v1_neighbours = v1.neighbours.copy()
v2_neighbours = v2.neighbours.copy()
# for every Vertex in v1.neighbours, check if there is a corresponding Vertex in v2.neighbours
# if there is, remove that Vertex from both lists
for n1 in v1_neighbours:
for n2 in v2_neighbours:
if n1.label == n2.label:
v1_neighbours.remove(n1)
v2_neighbours.remove(n2)
break
else:
return False
if len(v1_neighbours) == 0 and len(v2_neighbours) == 0:
return True
return False
I doubt this solution works: doesn't List.remove(element) remove all occurrences of that element? Also, I don't think it's memory efficient, which is important, as the neighborhoods will be pretty big.
Could anyone tell me how I can compare v1_neighbours and v2_neighbours properly, checking for an equal amount of duplicates while not altering the lists, without copying the lists?
collections.Counter(l1) == collections.Counter(l2)should do the trick