Timothy Wong
Timothy Wong

Reputation: 21

Returning the number of words in a list with a given number of vowels

Is there a way to edit this program so that it returns the number of words in a list with a given number of vowels?

I've tried but I can't seem to return the correct number and I don't know what my code is outputting.

(I'm a beginner)

def getNumWordsWithNVowels(wordList, num):
totwrd=0
x=0
ndx=0
while ndx<len(wordList):
    for i in wordList[ndx]:
        if(i=='a' or i=='e' or i=='i' or i=='o' or i=='u' or i=='A' or i=='E' or i=='I' or i=='O' or i=='U'):
            x+=1
        if x==num:
            totwrd+=1
        ndx+=1
return totwrd

print(getNumWordsWithNVowels(aList, 2))

This outputs "2" but it is supposed to output "5".

Upvotes: 0

Views: 67

Answers (1)

blhsing
blhsing

Reputation: 106883

You can use the sum function with a generator expression:

def getNumWordsWithNVowels(wordList, num):
    return sum(1 for w in wordList if sum(c in 'aeiou' for c in w.lower()) == num)

so that:

aList = ['hello', 'aloha', 'world', 'foo', 'bar']
print(getNumWordsWithNVowels(aList, 1))
print(getNumWordsWithNVowels(aList, 2))
print(getNumWordsWithNVowels(aList, 3))

outputs:

2 # world, bar
2 # hello, foo
1 # aloha

Upvotes: 1

Related Questions