How to determine if a list is a subset of another list?

I know how to determine if a list is a subset of another list. But I was wondering how you make sure the list is an ordered subset of another list. By ordered subset, I mean that the items in both lists are in the same order

For example, if I have the following lists

A = [1,2,3]
B = [1,2]
C = [2,1]

Here B is an ordered subset of A, but C is not (although A has all the elements of C)

+4
source share
4 answers

Use a simple loop to iterate over both lists in order. In the end, make sure that all elements of the list of potential subsets are visible.

i,j = 0,0
while i < len(A) and j < len(B):
    if A[i] == B[j]:
        j += 1
    i += 1

has_as_subset = (j == len(B))
+3
source
def is_sub(sub, lst):
    ln = len(sub)
    for i in range(len(lst) - ln + 1):
        if all(sub[j] == lst[i+j] for j in range(ln)):
            return True
    return False

Output:

In [21]: A = [4, 3, 2, 1, 2, 3]

In [22]: B = [1, 2]

In [23]: C = [2, 1]

In [24]: is_sub(B, A)
Out[24]: True

In [25]: is_sub(C, A)
Out[25]: True
In [26]: B = [10,11,12,13,14,15,25]
In [27]: is_sub(B, A)
Out[27]: False
In [39]: A = [1, 2, 1, 2, 1, 2, 3]
In [40]: B = [1, 2, 3]

In [41]: is_sub(B, A)
Out[41]: True

, sub lst, , , False.

:

def is_sub(s, l):
    ln = len(s)
    return any((all(s[j] == l[i + j] for j in range(ln))
                for i in range(len(l) - ln + 1)))

:

def is_sub(sub, lst):
    ln = len(sub)
    return any(lst[i: i + ln] == sub for i in range(len(sub) - ln + 1))

, , kfx, :

def is_sub_with_gap(sub, lst):
    ln, j = len(sub), 0
    for ele in lst:
        if ele == sub[j]:
            j += 1
        if j == ln:
            return True
    return False

, :

In [6]: a,b = [1,2,3,4], [1,2,4]

In [7]: is_sub(b,a)
Out[7]: False

In [8]: is_sub_with_gap(b,a)
Out[8]: True
+1
a_i = 0
for b in B:
    try:
        if b == A[a_i]:
            a_i += 1
    except IndexError:
        return False
return True

, A, B.

0

, (.. is_sublist([1,2,4],[1,2,3,4]) True), ; , ( , , ); , False, - , (.. [1,2,2] - [1,2,3]): , . ( , - kfx.)

def is_sublist( sublst, lst ):
    for element in sublst:
        try: ind = lst.index( element )
        except ValueError: return False
        lst = lst[ ind+1: ]
    return True
0

Source: https://habr.com/ru/post/1622814/


All Articles