在一个杂乱的字符串中查找子字符串
在一个杂乱的字符串中查找子字符串
我正在写一个脚本- includes(word1, word2) - 它接受两个字符串作为参数,并查找word1是否包含在word2中。Word2是一堆字母。它应该返回布尔值。同样,允许字母重复,我只检查字母是否以相同的顺序包含在两个单词中。
>>>includes('queen', 'qwertyuytresdftyuiokn') True
\'queen\',\'QwertyUytrEsdftyuiokN\'
我尝试将每个单词转换为列表,以便更容易处理每个元素。我的代码是:
def includes(w1, w2): w1 = list(w1) w2 = list(w2) result = False for i in w1: if i in w2: result = True else: result = False return result
但问题是我还需要检查word1的字母是否以相同的顺序出现在word2中,而我的代码并没有控制这一点。我找不到一种使用列表实现这一点的方法。就像我无法在字符串上做太多事情一样,因此我认为我需要使用另一种数据结构,如字典,但我对它们不太了解。
admin 更改状态以发布 2023年5月21日
我希望我理解了你的目标。
Python 不是我的强项,但我认为我已经将它写成了 Pythonic 风格:
def is_subsequence(pattern, items_to_use): items_to_use = (x for x in items_to_use) return all(any(x == y for y in items_to_use) for x, _ in itertools.groupby(pattern))
Explanation:
- itertools.groupby 将
pattern
传递给组合,并丢弃了连续的重复项 - 所有分组后的
pattern
中的元素都必须满足条件 any
使用生成器items_to_use
直到它不匹配当前项。请注意,items_to_use
必须在最终表达式之外定义,以便每次验证pattern
的下一个项时保持其进展。