Find the counts of common items
Anonymous User
455

input: [('A','spoon'),('A','spoon'),('A','fork'),('B','fork'),('B','dish')]

For every two people, find the counts of common items.
i.e. output: [('A','A',2)('A','B',1)('B','B',2)('B','A',2)]

A, A both have spoon, fork => 2
A, B or B, A both have fork => 1
B, B both have fork, dish => 2

I build the dictionary {'A': set(spoon, fork), 'B': set(fork, dish)} then do a nested loop:

for key1, val1 in ...:
    for key2, val2 in ...:
        result.append(key1, key2, len(val1.intersection(val2)))

Could you please share other solutions? Thanks!

Comments (2)