there is a dictionary containning many lists, for example,
list_dic= {
q1:[1,2,3,4,5]
q2:[2,3,5]
q3:[2,5]
}
and I want to get all common items count for each list, e.g. the common items count for q1 and q2 is 3=(2,3,5)
q1={q2:3, q3:2}
q2={q1:3,q3:2}
q3={q1:2, q2:2}
my code for this task is:
result = {}
for name, source_list in list_dic.items():
for target_name, target_list in list_dic.items():
count = 0
for item in source_list:
if item in target_list:
count+=1
result[name][target_name] = count
but this algorithm is inefficient, I want to know a better algorithm to do this task
I think this should do it:
If you’re following the comments, it turns out that
combinationsis slightly faster thanpermutations:with the results:
This is because
set.intersectionis an O(min(N,M)) operation — Which is cheap, but can add up if you’re doing it twice as many times as you need to.