How do you find the intersection of two arrays, and what do the different interpretations of that word mean?
You put the first list into a set and then you keep the items of the second list that are in it.
def intersection(a, b):
seen = set(a)
return [value for value in b if value in seen]
print(intersection([1, 2, 3, 4], [3, 4, 5])) # [3, 4]
So what does the word intersection actually mean? There are three different questions that people ask with that word, and they have different answers.
The first one is which values are in both lists. That is the question above, and the answer is a set.
The second one is which values are in both, counting the repeats. So if the first list has two threes and the second has one three, the answer has one three. That is what you get when you count how often each value appears in each list and take the smaller of the two counts.
The third one is which values sit at the same place in both lists. That is a completely different question, and the answer has nothing to do with sets at all.
the question the answer
------------------------------------ -------------------------
which values appear in both? the set version
which values appear in both, with count each and take the
the repeats? smaller count
which values are at the same index? compare them one by one
So the answer to the question is this. Ask which one of the three you mean before you write the query, because the code for each one is different.
The next question in this topic looks at the version that also keeps the order right.