Number of duplicates between two lists

a = [1, 2, 9, 5, 1]
b = [9, 8, 7, 6, 5]

I want to count the number of duplicates between these two lists. Therefore, using the above, I want to return the score 2, because 9 and 5 are common to both lists.

I tried something like this, but it didn’t quite work.

def filter_(x, y):
    count = 0
    for num in y:
        if num in x:
            count += 1
            return count
+5
source share
4 answers

Shorter way and better:

>>> a = [1, 2, 9, 5, 1]
>>> b = [9, 8, 7, 6, 5]
>>> len(set(a) & set(b))     # & is intersection - elements common to both
2 

Why your code is not working:

>>> def filter_(x, y):
...     count = 0
...     for num in y:
...             if num in x:
...                     count += 1
...     return count
... 
>>> filter_(a, b)
2

Yours return countwas inside a for loop and returned without completion.

+16
source

You can use set.intersection:

>>> set(a).intersection(set(b)) # or just: set(a).intersection(b)
set([9, 5])

Or, for the length of the intersection:

>>> len(set(a).intersection(set(b)))
2

Or, more concise:

>>> len(set(a) & set(b))
2
+8
source

, ; -

from collections import Counter

def numDups(a, b):
    if len(a)>len(b):
        a,b = b,a

    a_count = Counter(a)
    b_count = Counter(b)

    return sum(min(b_count[ak], av) for ak,av in a_count.iteritems())

numDups([1,1,2,3], [1,1,1,1,1])

2. O (n + m).

,

for num in y:
    if num in x:
        count += 1

- [1,2,3,3] [1,1,1,1,1,3], 3, 6, ( 2).

+4
source

Convert them to setand count the intersection.

 len(set(a).intersection(set(b)))
+3
source

All Articles