I am learning and practising lambda functions and came across a question that I am not able to solve.
Q – Create a list of fruits with more than 2 vowels.
fruits = ['mango', 'kiwi', 'strawberry', 'guava', 'pineapple', 'mandarin orange']
My solution using a list comprehension:
result = [fruit for fruit in fruits if len([True for char in fruit if char in "aeiou"]) > 2]
This works well but I need to achieve the same output using a lambda function
My attempt using lambda function:
result2 = list(filter(lambda x : len(set("aeiou") & set(x)) > 2, fruits))
result2 creates a list of fruits with more than 2 different vowels, but I need a list containing fruits that just has more than 2 vowels.
Expected Output – ['guava', 'pineapple', 'mandarin orange']
Output – ['pineapple', 'mandarin orange']
>Solution :
You can achieve the desired output using a lambda function by modifying the lambda function to count the total number of vowels in each fruit rather than checking for unique vowels.
result2 = list(filter(lambda x: sum(1 for char in x if char in "aeiou") > 2, fruits))