Home > Mobile >  a list from a list comprehension, find number of vowels in a string
a list from a list comprehension, find number of vowels in a string

Time:04-06

i am trying to write a function which goes through a np.array which contains emails and i want to obtain the number of vowels that are present in the email in a form of array

my try is:

def number_of_vouls(email):
    vouls = 'aeiouAEIOU'
    name = [e.split('@')[0] for e in email]
    return [sum(1 for c in name if c in vouls) for n in name]

number_of_vouls(np.array(['[email protected]', '[email protected]']))

output: [0, 0]

The expected outout should be : [5, 4] for this case

My problem i think is that i am not able to loop by characters inside name but not sure how to solve it

CodePudding user response:

Just change name to n in the sum function

def number_of_vouls(email):
    vouls = 'aeiouAEIOU'
    name = [e.split('@')[0] for e in email]
    return [sum(1 for c in n if c in vouls) for n in name]

number_of_vouls(np.array(['[email protected]', '[email protected]'])

CodePudding user response:

You can do this instead :

emails = ["[email protected]","[email protected]"]

vowels = ["a","e","i","o","u"]
count = 0
result = []

for email in emails:
    words = email.split("@")
    for char in words[0]:
        if char.lower() in vowels:
            count =1

    result.append(count)

print(result)

CodePudding user response:

Another option could be:

def number_of_vouls(email):
    vouls = 'aeiouAEIOU'
    name = [e.split('@')[0] for e in email]
    return [len([a for a in n if vouls.find(a) != -1]) for n in name]

CodePudding user response:

There are many different ways to do this. Here's another method:

VOWELS = {*'aeiouAEIOU'}

def number_of_vowels(emails):
    result = []
    for email in emails:
        localpart, *_ = email.split('@')
        result.append(sum(map(lambda x: x in VOWELS, localpart)))
    return result

print(number_of_vowels(['[email protected]', '[email protected]']))

CodePudding user response:

Since you're working with numpy arrays, you might want to take a look at the vectorize function:

number_of_vouls = np.vectorize(lambda x: sum([1 if y in "aeiou" else 0 for y in x.split("@")[0].lower()]))
print(number_of_vouls(np.array(['[email protected]', '[email protected]'])))

CodePudding user response:

Used lower case vouls characters and then count them with casefold approach.

import numpy as np

def number_of_vouls(email):
    vouls = 'aeiou'
    names = [e.split('@')[0] for e in email]
    
    return [sum(name.casefold().count(v) for v in vouls) for name in names]
    
emails = np.array(['[email protected]', '[email protected]', '[email protected]'])
v = number_of_vouls(emails)

Output

[4, 4, 3]
  • Related