Dustin
Dustin

Reputation: 6307

Python - Best Matching from List

This is probably a simple script but can't seem to find a list on Google. I have a list that contains words, and then a phrase. I'd like to match the words in to list to the phrase, and then if it doesn't match to return false. How would I go about it using Python?

Example:

list = ["hello", "word", "game", "challenge", "play"]
phrase = "play game"

if 'any combination from list' == phrase:
    return True
else:
    return False

Upvotes: 1

Views: 97

Answers (4)

IcyFlame
IcyFlame

Reputation: 5199

This will also work:

words = ["hello", "word", "game", "challenge", "play"]
phrase = "play game"

p = phrase.split(" ");

for i in p:

    if not i in words:

        return False

return True

Its a very simple way to do this. Though it involves a few more lines of code. You can refer @Lattyware's Answer, Which I felt is the best way to do this!

Upvotes: 0

Stephan
Stephan

Reputation: 17971

list = ["hello", "word", "game", "challenge", "play"]
phrase = "play game"

if all((term in list) for term in phrase.split()):
    return True
else:
    return False

With the fewest possible changes to your code, this should make sure that EVERY word in your phrase is found the list.

If you wanted to make sure that ONE of the words in your phrase is in the list, change all() to any().

Upvotes: 2

Gareth Latty
Gareth Latty

Reputation: 88977

Due to the sheer number of permutations possible, it is far better to reverse your logic, and check if every word in the phrase is in your list.

words = {"hello", "word", "game", "challenge", "play"}
phrase = "play game"
return all(word in words for word in phrase.split())

We can achieve this very easily with the all() built-in function, and a generator expression.

We split the phrase into words with str.split(), then check each word to see if it is in words (the variable name list smashes the built-in list() function, and should not be used).

Note also the change to a set, as a membership test on a set is significantly faster than on a list. As a long phrase may do many membership tests in this function, we want that operation to be as efficient as possible.

A set literal just uses curly braces instead of square brackets - if you have an existing list, not a literal, you can just use the set() built-in function to construct a set. E.g: words = set(some_list).

Upvotes: 8

Nehar Arora
Nehar Arora

Reputation: 1

This should work:

import itertools
list = ["hello", "word", "game", "challenge", "play"]
phrase = "play game"

length  = len(phrase.split(' '))

for perm in itertools.permutations(list, length):
    if ' '.join(perm) == phrase:
        return True
    return False

Upvotes: 0

Related Questions