0

I know many similar questions has been asked before with answers but my concern is related to builtin functionality rather than my own logic of loops and indexes etc.

In my python app, I need to check if listA is subset of listB. I've done this with the help of sets like this

set(listA) < set(listB)

It works fine overall but I also need to check order of objects in list. e.g.

x = ['a','b','c','d']
xx = ['a', 'c']
xxx = ['c' , 'a']

so according to sets definition;

set(xx) < set(x) returns true and set(xxx) < set(x) also returns true...

But I need something that returns false for 2nd case.

Is there any builtin functionality in python or I need to implement my own logic to get required result?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Naila Akbar
  • 3,033
  • 4
  • 34
  • 76
  • 2
    I'm pretty sure you'll need to implement this manually. – Tim Pietzcker Sep 24 '18 at 07:21
  • There already are good answers here, just one question for clarification: What about a situation like `x = ['a','b','c','d'], xx = ['a', 'c', 'a']`? `set(xx) < set(x)` would return `True`, but I'm guessing the second test should fail? – Tim Pietzcker Sep 24 '18 at 07:32

1 Answers1

2

I think a better word for this operation is a subsequence.

You need to write this yourself, but you can do it fairly easily by walking both lists together:

def is_subsequence(a, b):
    b_it = iter(b)
    try:
        for a_val in a:
            while next(b_it) != a_val:
                pass
    except StopIteration:
        return False
    else:
        return True

used as:

>>> is_subsequence(xx, x)
True
>>> is_subsequence(xxx, x)
False

Edit: Searching for "subsequence" finds this great answer.

Eric
  • 95,302
  • 53
  • 242
  • 374