Python 用于检查一个列表是否是另一个列表的子列表的程序的断言测试

Python 用于检查一个列表是否是另一个列表的子列表的程序的断言测试,python,list,assert,sublist,Python,List,Assert,Sublist,我编写了一个小程序,可以检查给定列表是否是另一个列表的子列表,并返回True或False: def is_sublist_of(sublist, given): """ Returns whether the sublist is part of the given combination. The order of the sublist must also correspond to the order of the corresponding part in the

我编写了一个小程序,可以检查给定列表是否是另一个列表的子列表,并返回
True
False

def is_sublist_of(sublist, given):
    """ Returns whether the sublist is part of the given combination.
    The order of the sublist must also correspond to the order of the
    corresponding part in the given combination."""

    return sublist in [given[i:i+len(sublist)] for i in range(0,len(given)-len(sublist))]
此代码是我必须执行的任务的一部分,但给定的断言之一是:

simple_list = [1, 2, 3, 4]
for element in simple_list:
    assert is_sublist_of([element], simple_list)
assert not is_sublist_of([5], simple_list)

我的程序没有通过这个测试。这是否意味着我的程序在某些特殊情况下不起作用?感谢您对此进行研究。

范围不包括终点,因此您必须添加1,否则它将错过测试中的最后一个元素

range(0,len(given)-len(sublist)+1)

。您不会生成所有子列表:最后一个被忽略。如果给出
gived=[1,2,3,4]
子列表=[1]
,则得到:

>>> given = [1, 2, 3, 4]
>>> sublist = [1]
>>> [given[i:i+len(sublist)] for i in range(0,len(given)-len(sublist))]
[[1], [2], [3]]
(他们通常称之为“一次失误”)

快速修复方法是:

return sublist in [given[i:i+len(sublist)] for i in range(0,len(given)-len(sublist)+1)]
def is_sublist_of(sublist, given):
    n = len(sublist)
    return any(sublist == given[i:i+n] for i in range(len(given)-n+1))
在这里,算法将从找到此类列表的那一刻起停止,因此不会生成所有子列表,然后检查其中一个子列表是否匹配