Show only 2-vowel words from word list; only getting the first one

Question:

def vowels(list):
    res = []
    for word in list:
        vowel_n = 0
        for x in word:
            if x in 'aeiou':
                vowel_n+=1
                
                if vowel_n== 2:
                    res.append(word)
                    return res

print(vowels(['tragedy', 'proof', 'dog', 'bug', 'blastoderm']))

Result: [‘tragedy’]

I’m expecting to show all characters that only have 2 vowels

Asked By: Denzel

||

Answers:

Try reducing the indentation of the if vowel_n== 2: block by 2 levels (needs to be the same level with the inner loop). Currently, it’s not checking the vowel counter unless the letter is a vowel.

And move return to outside of the loop. You’re returning the result after the first word that matches the condition.

Check out this repl.it project: https://replit.com/@HarunYilmaz1/PrudentPalegreenScans#main.py

def vowels(word_list):
    res = []
    for word in word_list:
        vowel_n = 0
        for x in word:
            if x in 'aeiou':
                vowel_n+=1
                
        if vowel_n== 2:
            res.append(word)

    return res
Answered By: Harun Yilmaz

It’s probably a good idea to normalise the words to lowercase and work on that. Also, don’t use built-in function names as variables:

VSET = {'a', 'e', 'i', 'o', 'u'}

def vowels(lst):
    res = []
    for word in map(str.lower, lst):
        if sum(c in VSET for c in word) == 2:
            res.append(word)
    return res

print(vowels(['tragedy', 'proof', 'dog', 'bug', 'blastoderm']))

Output:

['tragedy', 'proof']
Answered By: Cobra

This solution heavily relies on list comprehensions.

"List comprehensions provide a concise way to create lists." [Python Documentation]

[letter for letter in word if letter in "aeiou"] iterates over the letters of a word (str is iterable) and creates a list made only of vowels.

By applying len() to this list we get the number of vowels in the word.

As we want to keep only the words which have 2 vowels, we iterate over the words and to do that we also use a list-comprehension : [word for word in words].

The "letter" list-comprehensions is nested in the "word" list-comprehension.

words = ['tragedy', 'proof', 'dog', 'bug', 'blastoderm']
print([word for word in words if len([letter for letter in word if letter in "aeiou"]) == 2])
Answered By: 0x0fba
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.