使用
bytes.find
以查找序列的出现。我的
i
告诉下一次发生的位置
预期
启动和
j
告诉它在哪里
事实上
启动。(框架大多抄袭自Samwise。)
def find_outliers(needle: list[int], haystack: list[int]) -> list[int]:
"""Find indices in haystack where
the sequence of repeated needles is broken."""
outliers: list[int] = []
i = 0
needle = bytes(needle)
find = bytes(haystack).find
while (j := find(needle, i)) != -1:
outliers += range(i, j)
i = j + len(needle)
outliers += range(i, len(haystack))
return outliers
assert not find_outliers(
[1, 1, 0],
[1, 1, 0, 1, 1, 0, 1, 1, 0]
)
assert find_outliers(
[1, 1, 0],
[1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0]
) == [6, 16]
assert find_outliers(
[1, 1, 0],
[1, 1, 0, 1, 1]
) == [3, 4]
Attempt This Online!