1

Write a function called sublist. The function takes 2 lists as parameters, and returns True if the items in the first list appear in the same order somewhere in the second list (and False if they don't)

Here are some examples:

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

Here's what I have so far:

def sublist(list1,list2):
    for i in range(len(list2)):
        if list2[i] != list1[i]:
            return False
        return True

output:

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

I know that's not entirely right and I know I'm going to have to use [ : ] to extract a portion of a string or a list but I have no idea where to start. Any help would be great, thank you.

yummyyenni
  • 23
  • 7

1 Answers1

1

Try this:

def sublist(list1, list2):
    n = len(list1)
    return any((list1 == list2[i:i + n]) for i in range(len(list2) - n + 1))

print sublist([2, 3], [1, 2, 3, 4, 5])
print sublist([1, 3], [1, 2, 3, 4, 5])
print sublist([1, 2, 3], [1, 2, 1, 2, 3, 4])

We need to know the length of the sublist, that's what n is for.

Then the any() will stop after the first match in the iterable. The part inside the any() is a generator, we're comparing the sublist (list1) with each of the sublists in list2, starting from the beginning up to the end.

i will range from 0 up to the length of the second list, but you subtract out the length of the first list and then add 1, so you don't go over the end of the index.

jgritty
  • 11,660
  • 3
  • 38
  • 60