Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python – Need help converting a list comprehension to a lambda function

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading