Suppose listA=[[0,1],[1,2]], which stores two 2-combinations from {0,1,2,3}. listB=[[0,1,2],[0,1,3],[0,2,3],[1,2,3]], which stores all possible 3-combinations from {0,1,2,3}.
How to find all elements in listB that include/contain at least one of the 2-combinations from listA?
My desired output is listC=[[0,1,2],[0,1,3],[1,2,3]], where [0,1,2] includes both [0,1] and [1,2], [0,1,3] includes [0,1], [1,2,3] includes [1,2].
Thanks!(It would be great if the answer codes is efficient and fast, as I need to do this for listA and listB that are of large scale)
I tried the following codes:
import numpy as np
import itertools
listA=[[0,1],[1,2]]
listB=[]
listCdup=[]
rows=range(4)
for combo in itertools.combinations(rows, 3):
listB.append(list(combo))
print(listB)
for b in listB:
for a in listA:
if a.issubset(b):
listCdup.append(b)
listC=np.unique(listCdup)
But there is an error that says list object has no attribute 'issubset'
CodePudding user response:
Hope this code can be a solution for your scenario, let me know if you think it needs any explanations:
listA=[[0,1],[1,2]]
listB=[[0,1,2],[0,1,3],[0,2,3],[1,2,3]]
res = []
for comA in listA:
strA = " ".join(str(e) for e in comA)
for comB in listB:
strB = " ".join(str(el) for el in comB)
if strA in strB:
res.append(list(comB))
print(res)
CodePudding user response:
Here is a solution using itertools.combinations, comprehensions, and set:
>>> from itertools import combinations
>>> a = [(0, 1), (1, 2)]
>>> a
[(0, 1), (1, 2)]
>>> b = list(combinations(range(4), 3))
>>> b
[(0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3)]
>>> c = set(bi for ai in a for bi in b if ai in set(combinations(bi, len(ai))))
>>> c
{(0, 1, 2), (0, 1, 3), (1, 2, 3)}
>>>
The solution above assumes that len(ai) <= len(bi) where ai and bi are elements of a and b, respectively. What it does is simply check if each element of a is an element of the combinations of each element of b combined by the len() of elements of a.
