Austin
Austin

Reputation: 4566

Python - match letters of words in a list

I'm trying to create a simple program where a user enters a few letters

Enter letters: abc

I then want to run through a list of words I have in list and match and words that contain 'a','b', and 'c'.

This is what I've tried so far with no luck

for word in good_words: #For all words in good words list
    for letter in letters: #for each letter inputed by user
        if not(letter in word):
            break
    matches.append(word)

Upvotes: 2

Views: 4934

Answers (4)

Joel Cornett
Joel Cornett

Reputation: 24788

List comprehensions are definitely the way to go, but just to address the issue that OP was having with his code:

Your break statement only breaks out of the innermost loop. Because of that the word is still appended to matches. A quick fix for this is to take advantage of python's for... else construct:

for word in good_words:
    for letter in letters:
        if letter not in word:
            break
    else:
        matches.append(word)

In the above code, else only executes if the loop is allowed to run all the way through. The break statement exits out of the loop completely, and matches.append(..) is not executed.

Upvotes: 1

ephemient
ephemient

Reputation: 204678

import collections

I would first compute the occurrences of letters in the words list.

words_by_letters = collections.defaultdict(list)
for word in good_words:
    key = frozenset(word)
    words_by_letters[key].append(word)

Then it's simply a matter of looking for words with particular letter occurrences. This is hopefully faster than checking each word individually.

subkey = set(letters)
for key, words in words_by_letters.iteritems():
    if key.issuperset(subkey):
        matches.extend(words)

If you want to keep track of letter repeats, you can do something similar by building a key from collections.Counter.

Upvotes: 0

JBernardo
JBernardo

Reputation: 33387

If you want all the letters inside the word:

[word for word in good_words if all(letter in word for letter in letters)]

The problem with your code is the break inside the inner loop. Python doesn't have a construction to allow breaking more than one loop at once (and you wanted that)

Upvotes: 10

Jeremy D
Jeremy D

Reputation: 4855

You could probably improve the spee using a Set or FrozenSet

If you look at the doc, it mentionned the case of testing membership :

A set object is an unordered collection of distinct hashable objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference.

Upvotes: 2

Related Questions