Reputation: 321
I need to write a function for returning a list by filtering it by vowel count.
I tried this but output is incorrect:
def filter_by_vowel_count(input, count):
for words in input:
for p in words:
if p in 'aeiou':
value +=1
if value == count:
list1.append(words)
Upvotes: 1
Views: 1841
Reputation: 122106
Your problems are with indentation, resetting and returning:
for words in input:
value = 0 # reset vowel count
for p in words:
if p in 'aeiou':
value +=1
if value == count: # should be outside for loop
list1.append(words)
return list1 # return the new list
As others have pointed out, there are also neater ways to achieve what you want.
Upvotes: 0
Reputation: 16940
Using regex:
import re
def filter( ls, c ):
find = [ (s,len(re.findall("[aeiou]", s))) for s in ls ]
return [ x for x in find if x[1] == c ]
fruits = ['banana', 'apple', 'lemon', 'pineapple', 'coconut']
print filter(fruits, 2)
print filter(fruits, 3)
Output:
[('apple', 2), ('lemon', 2)]
[('banana', 3), ('coconut', 3)]
Upvotes: 0
Reputation: 58975
I can greatly simplify your life using the built-in collections.Counter
class:
from collections import Counter
def filter(fruits, num):
num_of_vowels = [sum([c[k] for k in 'aeiou']) for c in [Counter(f) for f in fruits]]
return [f for i,f in enumerate(fruits) if num_of_vowels[i]==num]
Upvotes: 0
Reputation: 5271
words = [] # list of strings
vowels = "aeiou"
filter(lambda x: sum(x.count(c) for c in vowels) == count, words )
Upvotes: 0
Reputation: 369334
Using sum
and generator expression:
>>> def filter_by_vowel_count(words, count):
... result = []
... for word in words:
... if sum(p in 'aeiou' for p in word) == count:
... result.append(word)
... return result
...
>>> fruits = ['banana', 'apple', 'lemon', 'pineapple', 'coconut']
>>> filter_by_vowel_count(fruits, 2)
['apple', 'lemon']
>>> filter_by_vowel_count(fruits, 3)
['banana', 'coconut']
Upvotes: 2