Determine if all elements in a list are present and in the same order in another list

后端 未结 10 1176
难免孤独
难免孤独 2021-01-02 15:35

How do I create a function sublist() that takes two lists, list1 and list2, and returns True if list1 is a s

10条回答
  •  粉色の甜心
    2021-01-02 16:02

    Here's an iterative solution which should have optimal asymptotics:

    def sublist(x, y):
        if x and not y:
            return False
        i, lim = 0, len(y)
        for e in x:
            while e != y[i]:
                i += 1
                if i == lim:
                    return False
            i += 1
        return True
    

    @sshashank124's solution has the same complexity, but the dynamics will be somewhat different: his version traverses the second argument multiple times, but because it pushes more work into the C layer it'll probably be much faster on smaller input.

    Edit: @hetman's solution has essentially the same logic, but is much more Pythonic, although, contrary to my expectation, it seems to be slightly slower. (I was also incorrect about the performance of @sshashan124's solution; the overhead of the recursive calls appears to outweigh the benefit of doing more work in C.)

提交回复
热议问题