How to check if all sequence keyword matched in string? – Python

Question:

I have a list of keywords(the number of keywords is depended on user input), I want to check if all keywords are in a sentence with sequence in list.

example of keywords(order of keywords is needed for comparing):

keywords = ['Hello', 'my', 'friend']

case should return false

sentence = ['Dear', 'my', 'friend', 'Hello']

case should return true

sentence = ['Hello', 'my', 'Dear', 'friend']

Here is my code:

keywords = ['Hello', 'my', 'friend']
    sentence = ['Dear', 'my', 'friend', 'Hello']
    marker = 0
    for keyword in keywords:
        for word in sentence:
            if keyword == word:
                marker = sentence.index(word) - marker
                if marker < 0:
                    return False
    return True

Is there any algorithm I can use to optimize my code? Because once I have duplicated word in sentence it doesn’t work

Asked By: Neruru

||

Answers:

You can create an iterator from the given sentence, and iterate over the keywords to test if each keyword is found in the sequence generated by the iterator, which follows the order of words in the given sentence:

def matches_sequence(keywords, sentence):
    sequence = iter(sentence)
    return all(keyword in sequence for keyword in keywords)

so that:

keywords = ['Hello', 'my', 'friend']
print(matches_sequence(keywords, ['Dear', 'my', 'friend', 'Hello']))
print(matches_sequence(keywords, ['Hello', 'my', 'Dear', 'friend']))

outputs:

False
True

Demo: https://replit.com/@blhsing/SkinnyClumsyInterchangeability

Answered By: blhsing
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.