Python:How to check if a list is a sublist of another list with duplicate values

Viewed 523

Example:

lista = ['p','o','o','p']
listb = ['p','o','o','h','a','b','c']

if I use the issubset method, it will turn out to be True. When in fact lista is not a subset of listb. I'm coding in python by the way. To clarify, the code has to work in this case:

lista = ['p','o','o','p']
listb = ['p','o','o','h','p','b','c']

The above shall return true.

But,

lista = ['p','o','o','p']
listb = ['p','o','h','p','b','c']

The above will be false. The first example is also false.

4 Answers

You can join the lists to strings and check if one is part of the other:

lista = ['p','o','o','p']
listb = ['p','o','o','h','a','b','c']
''.join(lista) in ''.join(listb)
False


lista = ['p','o','o','p']
listb = ['p','o','o','p','h','a','b','c']
''.join(lista) in ''.join(listb)
True

I doubt you can do it in less than O(N), by direct comparison.

This is an option:

def issublist(list_a, list_b):
    for i in range(len(list_b)-len(list_a)):
        if list_a == list_b[i:len(list_a)+i]:
            return True
    return False

Oneliner:

any([lista==listb[i:i+len(lista)] for i in range(len(listb)-len(lista)+1)])

Try this:

def removeElements(a, b): 
    n = len(a) 
    return any(a == b[i:i + n] for i in range(len(b)- n + 1)) 

print(removeElements(a, b))
Related