在一个杂乱的字符串中查找子字符串

26 浏览
0 Comments

在一个杂乱的字符串中查找子字符串

我正在写一个脚本- 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日
0
0 Comments

如果你不仅仅是检查子字符串:

def include(a, b):
    a = "".join(set(a)) # removes duplicates
    if len(a) == 1:
        if a in b:
            return True
        else:
            return False
    else:
        try: 
            pos = b.index(a[0])
            return include(a[1:], b[pos:])
        except:
            return False
print(include('queen', 'qwertyuytresdftyuiokn'))
#True

0
0 Comments

我希望我理解了你的目标。
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))

https://ideone.com/Saz984

Explanation:

  • itertools.groupbypattern 传递给组合,并丢弃了连续的重复项
  • 所有分组后的 pattern 中的元素都必须满足条件
  • any 使用生成器 items_to_use 直到它不匹配当前项。请注意,items_to_use 必须在最终表达式之外定义,以便每次验证 pattern 的下一个项时保持其进展。
0