gpt4 book ai didi

python - 查找子序列(非连续的)

转载 作者:太空狗 更新时间:2023-10-29 17:05:15 25 4
gpt4 key购买 nike

如果我有字符串 needle我想检查它是否作为 substringhaystack 中连续存在,我可以使用:

if needle in haystack:
...

在非连续子序列的情况下我可以使用什么?示例:

>>> haystack = "abcde12345"
>>> needle1 = "ace13"
>>> needle2 = "123abc"
>>> is_subsequence(needle1, haystack)
True
>>> is_subsequence(needle2, haystack) # order is important!
False

最佳答案

不知道有没有自带的功能,手动操作还是比较简单的

def exists(a, b):
"""checks if b exists in a as a subsequence"""
pos = 0
for ch in a:
if pos < len(b) and ch == b[pos]:
pos += 1
return pos == len(b)
>>> exists("moo", "mo")
True
>>> exists("moo", "oo")
True
>>> exists("moo", "ooo")
False
>>> exists("haystack", "hack")
True
>>> exists("haystack", "hach")
False
>>>

关于python - 查找子序列(非连续的),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29954748/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com