John Smith
John Smith

Reputation: 45

Check if index of elements in two lists are consecutive

If list1 is defined as [15,1,20] and list2 is defined as [6,15,3,1,6,20]

The function will return True because list 2 contains (15,1,20) in the same order.

However if list 2 was defined as [6,1,15,20,3], the sequence is (1,15,20) therefore it will return False.

def sublist(lst1,lst2):
    for i in lst1:
        if i in lst2:
            if ## ?? ##
                return True
    return False

The if statement is where I am confused because I'm not sure how to check for consecutive numbers in two different lists.

Upvotes: 0

Views: 924

Answers (3)

Martijn Pieters
Martijn Pieters

Reputation: 1121524

Take a single item from the input list and scan forward over the second list until you have a match, then take the next item, continue forward, etc.

Using iterators, taking the next value to test is simple enough. Create an iterator for lst1 with iter(), and then the next() function gives you the next item in the list order. When that call raises StopIteration you know you have tested all the values in the first list:

def sublist(lst1, lst2):
    source = iter(lst1)
    try:
        item = next(source)
        for value in lst2:
            if item == value:
                item = next(source)
        return False
    except StopIteration:
        # all items in lst1 checked
        return True

Demo:

>>> lst1 = [15, 1, 20]
>>> sublist(lst1, [6, 15, 3, 1, 6, 20])
True
>>> sublist(lst1, [6, 1, 15, 20, 3])
False

Note that the function also returns True if lst1 is empty (the empty list is always an ordered subset) and False if lst1 is not empty but lst2 is (an empty list can never be a superset).

Upvotes: 2

user2390182
user2390182

Reputation: 73450

The following will work, based on the list.index method's start parameter:

def sublist(lst1, lst2):
    ind = 0
    for a in lst1:
        try:
            ind = lst2.index(a, ind)
        except ValueError:
            return False
    return True

>>> sublist([1,2,3], [4,1,3,2,5])
False
>>> sublist([1,2,3], [4,1,2,5,3])
True

This iteratively looks up the elements of lst1 in lst2 while moving ahead the start index for the lookup appropriately until any element can't be found in the remainder of lst2 or all are found.

Upvotes: 1

usernamenotfound
usernamenotfound

Reputation: 1580

get the index list for each item in the original list in the second list and check if any combination of them are in ascending order

Upvotes: 0

Related Questions