'Is there a efficient way to find only the combinations of interest from V exciting in P
Is there a efficient way to find only the combinations of interest from V exciting in P
I have a list of something like this.
V = [2,3,5,7,9,12]
Size of V can be anywhere from 0 to 50 based on my input. V has no duplicates.
I have another list P something like this
P = [ [1],[1,2],[2,3] [3,4], [3,5,7], [3,5,8] ...]
P is constant with size 1000.
P has no duplicates and within P, each element is sorted in ascending order.
What would be an efficient way to find the combinations from V existing in P.
For example
When V = [2,3,5,7,9,12] combination of interest would be [[2,3],[3,5,7]].
I have already tried generating all possible arrangements from V and then filter by P. This is not very efficient. Just wondering if there is a better way to do what I asked for.
Since I already know P is any form of Tree a better option for this ?
Solution 1:[1]
Using set.issuperset is probably the fastest method in practice:
v = set(V)
[c for c in P if v.issuperset(c)]
It is also possible to use two pointers, gradually advancing along each list. It will probably be slower in Python, but faster in C/C++:
def is_subset(V, combination):
# both V and combination are assumed sorted
v = iter(V)
for element in combination:
for el in v:
if el >= element:
break
if el != element:
return False
return True
[c for c in P if is_subset(V, c)]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Marat |
