nom*_*432 3 python assert list 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 given combination."""
return sublist in [given[i:i+len(sublist)] for i in range(0,len(given)-len(sublist))]
Run Code Online (Sandbox Code Playgroud)
此代码是我必须执行的赋值的一部分,但给定的断言之一是:
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)
Run Code Online (Sandbox Code Playgroud)
我的程序未通过此测试.这是否意味着我的程序在某些特殊情况下不起作用?感谢您对此进行调查.
是的.您不会生成所有子列表:省略最后一个.如果你给,given = [1,2,3,4]并sublist = [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]]
Run Code Online (Sandbox Code Playgroud)
(他们称这通常是" 一个错误 ").
快速解决方案是:
return sublist in [given[i:i+len(sublist)] for i in range(0,len(given)-len(sublist)+1)]Run Code Online (Sandbox Code Playgroud)
所以+1在range(..).
但更优雅的解决方案是:
def is_sublist_of(sublist, given):
n = len(sublist)
return any(sublist == given[i:i+n] for i in range(len(given)-n+1))Run Code Online (Sandbox Code Playgroud)
这里算法将从找到这样的列表的那一刻起停止,因此不生成所有子列表,然后检查它们中的一个是否匹配.