1

The ideal results below:

    >>> count_number_of_each_vowel("Zoo")
    {'o': 2}
    >>> count_number_of_each_vowel("Anaconda")
    {'a': 3, 'o': 1}
    >>> count_number_of_each_vowel("Programming and Data Analysis")
    {'o': 1, 'a': 6, 'i': 2}
    

Broken/Incomplete code:

def count_number_of_each_vowel(x: str) -> dict:
    x = x.lower()
    vowel_counts = []
    for vowel in "aeiou":
        count = lowercase.count(vowel)
        vowel_counts[vowel] = count
    return vowel_counts

Please help fix this broken code

PTP_XX
  • 59
  • 1
  • 7
  • Does this answer your question? [Count Vowels in String Python](https://stackoverflow.com/questions/19967001/count-vowels-in-string-python) – sahasrara62 Nov 01 '21 at 07:07

3 Answers3

1

One of the many approaches:

from collections import defaultdict
def count_number_of_each_vowel(data):
    out = defaultdict(lambda:0)
    for word in data.lower():
        if word in "aeiou":
            out[word]+=1
            
    return dict(out)
print (count_number_of_each_vowel("Programming and Data Analysis"))

Output:

{'o': 1, 'a': 6, 'i': 2}
Bhagyesh Dudhediya
  • 1,800
  • 1
  • 13
  • 16
0

Example:

a_string = "Anaconda"
lowercase = a_string.lower()
vowel_counts = {}

for vowel in "aeiou":
    count = lowercase.count(vowel)

    vowel_counts[vowel] = count


print(vowel_counts)

Output:

>>> print(vowel_counts)
{'a': 3, 'e': 0, 'i': 0, 'o': 1, 'u': 0}

Code Source: https://www.kite.com/python/answers/how-to-count-the-vowels-in-a-string-in-python

PTP_XX
  • 59
  • 1
  • 7
0

I'd prefer collections.Counter:

from collections import Counter

def count_number_of_each_vowel(s):
    return Counter([i for i in s.lower() if i in 'aeiou'])

>>> count_number_of_each_vowel("Zoo")
Counter({'o': 2})
>>> 

Or with regex:

from collections import Counter
import re

def count_number_of_each_vowel(s):
    return Counter(re.sub('[^aeiou]', '', s.lower()))

>>> count_number_of_each_vowel("Zoo")
Counter({'o': 2})
>>> 
U13-Forward
  • 69,221
  • 14
  • 89
  • 114