I want to efficiently find the intersection of two lists , keeping duplicates from both, e.g. A=[1,1,2,3], B=[1,1,2,4] should return [1,1,1,1,2]
I know a similar question was asked previously (Python intersection of two lists keeping duplicates) however this does not help me because only the duplicates from one list are retained.
The following works
def intersect(A,B):
C=[]
for a in A:
for b in B:
if a==b:
C.append(a)
return C
however it isn't efficient enough for what I'm doing! To speed things up I tried sorting the lists
def intersect(A,B):
A.sort()
B.sort()
C=[]
i=0
j=0
while i<len(A) and j<len(B):
if A[i]<=B[j]:
if A[i]==B[j]:
C.append(A[i])
i+=1
else:
j=j+1
return C
however this only keeps the duplicates from list B. Any suggestions?