Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding a substring in a jumbled string

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', '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

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.

like image 742
arty Avatar asked Dec 18 '25 07:12

arty


1 Answers

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

Explanation:

  • 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.
like image 103
Marek R Avatar answered Dec 21 '25 01:12

Marek R