在混乱的字符串中查找子字符串 [英] Finding a substring in a jumbled string

查看:72
本文介绍了在混乱的字符串中查找子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个脚本-includes(word1,word2)-以两个字符串作为参数,并查找word2中是否包含word1.Word2是一个字母混乱.它应该返回布尔值.同样允许重复字母,我只检查两个单词中是否包含字母的顺序相同.

I am writing a script - includes(word1, word2) - that takes two strings as arguments, and finds if word1 is included in word2. Word2 is a letter jumble. It should return Boolean. Also repetition of letters are allowed, I am only checking if the letters are included in the both words in the same order.

>>>includes('queen', 'qwertyuytresdftyuiokn')
True

'queen',' Q werty U ytr E sdftyuiok N "

'queen', 'QwertyUytrEsdftyuiokN'

我尝试将每个单词转换为列表,以便更轻松地使用每个元素.我的代码是这样的:

I tried turning each word into lists so that it is easier to work with each element. My code is this:

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中的顺序是否相同,而我的代码对此没有控制.我找不到用list来实现的方法.就像我不能对字符串做太多事情一样,所以我认为我需要使用其他数据结构(例如字典),但我对它们了解不多.

But the problem is that I need to also check if the letters of word1 comes in the same order in word2, and my code doesn't controls that. I couldn't find a way to implement that with list. Just like I couldn't do this much with strings, so I think I need to use another data structure like dictionary but I don't know much about them.

推荐答案

我希望我了解您的目标是什么.
Python不是我的事,但我认为我是pythonic的:

I hope I understood what is your goal.
Python is not my thing, but I think I made it 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

说明:

  • itertools.groupby 传输 pattern ,以使本构重复项被丢弃
  • 分组为 pattern 的表单中的
  • 所有项必须满足条件
  • any 使用生成器 items_to_use ,只要它与当前项目不匹配即可.请注意,必须在最终表达式之外定义 items_to_use ,因此每次验证 pattern 中的下一个项目时,都会保持进度.
  • itertools.groupby transfers pattern in such way that constitutive duplicates are discarded
  • all items form form grouped pattern must fulfill conditions
  • any uses generator items_to_use as long as it doesn't matches current item. Note that items_to_use mus be defined outside of final expression so progress on it is kept every time next item from pattern is verified.

这篇关于在混乱的字符串中查找子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆