LaffyTaffyKidd
LaffyTaffyKidd

Reputation: 47

Finding the number of words with all vowels

I am given a text file that is stored in a list called words_list:

if __name__ = "__main__":
    words_file = open('words.txt')

    words_list = []
    for w in words_file:
        w = w.strip().strip('\n')
        words_list.append(w)

That's what the list of strings look like (it's a really, really long list of words)

I have to find "all the words" with all of the vowels; so far I have:

def all_vowel(words_list):
    count = 0
    for w in words_list:
        if all_five_vowels(w):   # this function just returns true
            count = count + 1
    if count == 0
        print '<None found>'
    else 
        print count

The problem with this is that count adds 1 every time it sees a vowel, whereas I want it to add 1 only if the entire word has all of the vowels.

Upvotes: 0

Views: 4274

Answers (3)

steveha
steveha

Reputation: 76725

@Martijn Peters has already posted a solution that is probably the fastest solution in Python. For completeness, here is another good way to solve this in Python:

vowels = set('aeiou')

with open('words.txt') as words_file:
    for word in words_file:
        word = word.strip()
        if all(ch in vowels for ch in word):
            print word

This uses the built-in function all() with a generator expression, and it's a handy pattern to learn. This reads as "if all the characters in the word are vowels, print the word." Python also has any() which could be used for checks like "if any character in the word is a vowel, print the word".

More discussion of any() and all() here: "exists" keyword in Python?

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1123360

Simply test if any of your words are a subset of the vowels set:

vowels = set('aeiou')

with open('words.txt') as words_file:
    for word in words_file:
        word = word.strip()
        if vowels.issubset(word):
            print word

set.issubset() works on any sequence (including strings):

>>> set('aeiou').issubset('word')
False
>>> set('aeiou').issubset('education')
True

Upvotes: 6

Jesse
Jesse

Reputation: 317

Assuming the word_list variable is an actual list, probably your "all_five_vowels" function is wrong.

This could be an alternative implementation:

def all_five_vowels(word):
    vowels = ['a','e','o','i','u']
    for letter in word:
        if letter in vowels:
            vowels.remove(letter)
            if len(vowels) == 0:
                return True
    return False

Upvotes: 3

Related Questions