Question

I've had a look around and seen a million and one questions like this, but none quite how I am trying to do this, so please be gentle!

Basically I'm trying to add the vowels in a sentence to a list??? and print the list, all this by using a lambda called isVowel, and a function called vowelFilter.

I am really unsure how to do this using a lambda, and what I have done so far doesn't seem to work, here's my code;

sentence = "The quick brown fox jumps over the bridge"
vowels = "aeiouAEIOU"
finalVowel = []
def vowelFilter(sentence):
        for letter in sentence:
                if letter in vowels:
                        finalVowel.append(letter)
        return finalVowel

Can you guys shed any light on this? Again I'm well aware this has been asked 1000000000x times but nothing that is 100% like mine, so please be kind!

Thanks

Was it helpful?

Solution 3

Using a lambda expression here is not very pythonic, but if you must:

sentence = "The quick brown fox jumps over the bridge"
vowels = "aeiouAEIOU"
finalVowel = []

# Return True if arg is in vowels; otherwise, return False
isVowel = lambda arg: arg in vowels

def vowelFilter(sentence):
    for letter in sentence:
        if isVowel(letter):  # Call the lambda to test if letter is a vowel
            finalVowel.append(letter)
    return finalVowel

print (vowelFilter(sentence))

From the docs:

lambda_expr ::= "lambda" [parameter_list]: expression

old_lambda_expr ::= "lambda" [parameter_list]: old_expression

Lambda expressions (sometimes called lambda forms) have the same syntactic position as expressions. They are a shorthand to create anonymous functions; the expression lambda arguments: expression yields a function object. The unnamed object behaves like a function object defined with

def name(arguments): return expression

See section Function definitions for the syntax of parameter lists. Note that functions created with lambda expressions cannot contain statements.

OTHER TIPS

You can use a list comprehension with a condition. There is no need for a lambda:

>>> l = [v for v in sentence if v in vowels]
>>> print l
['e', 'u', 'i', 'o', 'o', 'u', 'o', 'e', 'e', 'i', 'e']

Just

finalVowel = [x for x in sentence if x in vowels]

I hope this can help you

If it's a must to use lambda then you can do it like this (Which is not different than the other two answers)

vowel_filter = lambda sent: [x for x in sent if x in vowels]
vowel_filter(sentence)
>>> ['e', 'u', 'i', 'o', 'o', 'u', 'o', 'e', 'e', 'i', 'e']

finalVowel = vowel_filter(sentence)
print finalVowel
>>> ['e', 'u', 'i', 'o', 'o', 'u', 'o', 'e', 'e', 'i', 'e']
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top