It isn't clear how duplicates are handled when performing an intersection of lists which contain duplicate elements, as you have given only one test case and its expected result, and you did not explain duplicate handling.
According to how keeping duplicates work currently, the common elements are 'a'
and 'b'
, and the intersection list lists 'a'
with multiplicity 1 and 'b'
with multiplicity 2. Note 'a'
occurs once on both lists a and b, but 'b'
occurs twice on b. The intersection list lists the common element with multiplicity equal to the list having that element at the maximum multiplicity.
The answer is yes. However, a loop may implicitly be called - though you want your code to not explicitly use any loop statements. This algorithm, however, will always be iterative.
Step 1: Create the intersection set, Intersect
that does not contain duplicates (You already done that). Convert to list to keep indexing.
Step 2: Create a second array, IntersectD
. Create a new variable Freq
which counts the maximum number of occurrences for that common element, using count
. Use Intersect
and Freq
to append the element Intersect[k]
a number of times depending on its corresponding Freq[k]
.
An example code with 3 lists would be
a = ['a','b','c','1','1','1','1','2','3','o']
b = ['a','b','b','o','1','o','1']
c = ['a','a','a','b','1','2']
intersect = list(set(a) & set(b) & set(c)) # 3-set case
intersectD = []
for k in range(len(intersect)):
cmn = intersect[k]
freq = max(a.count(cmn), b.count(cmn), c.count(cmn)) # 3-set case
for i in range(freq): # Can be done with itertools
intersectD.append(cmn)
>>> intersectD
>>> ['b', 'b', 'a', 'a', 'a', '1', '1', '1', '1']
For cases involving more than two lists, freq
for this common element can be computed using a more complex set intersection and max expression. If using a list of lists, freq
can be computed using an inner loop. You can also replace the inner i-loop with an itertools expression from How can I count the occurrences of a list item?.