Counting How Many Times Each Vowel Appears

Counting how many times each vowel appears

The problem is with this line:

vowelCounts = [aCount, eCount, iCount, oCount, uCount] = (0,0,0,0,0)

vowelCounts does not get updated if you start incrementing aCount later.

Setting a = [b, c] = (0, 0) is equivalent to a = (0, 0) and [b, c] = (0, 0). The latter is equivalent to setting b = 0 and c = 0.

Reorder your logic as below and it will work:

aCount, eCount, iCount, oCount, uCount = (0,0,0,0,0)

for word in wordlist:
for letter in word:
# logic

vowelCounts = [aCount, eCount, iCount, oCount, uCount]

for vowel, count in zip(vowels, vowelCounts):
print('"{0}" occurs {1} times.'.format(vowel, count))

Indicate which vowel occurs the most in a string

There can be many ways. I am writing one of them. You can try it:

// for number of VOWELS
for (int i = 0; i < str.length(); i++)
{
ch = str.charAt(i);
ch = Character.toLowerCase(ch);

// is this a vowel
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
{
vowels++;
}

// which vowel occurs the most
if (ch == 'a')
vowelA++;
else if (ch == 'e')
vowelE++;
else if (ch == 'i')
vowelI++;
else if (ch == 'o')
vowelO++;
else if (ch == 'u')
vowelU++;

}

maxVowels = Math.max(vowelA, Math.max(vowelE, Math.max(vowelI, Math.max(vowelO, vowelU))));

Output:

enter image description here

Note: I have just added maxVowels = Math.max(vowelA, Math.max(vowelE, Math.max(vowelI, Math.max(vowelO, vowelU)))); before upper case logic and removed if-condition where you are storing maxVowels value.

Another Way: Replace maxVowels = Math.max(vowelA, Math.max(vowelE, Math.max(vowelI, Math.max(vowelO, vowelU)))); with Collections.max(Arrays.asList(vowelA, vowelE, vowelI, vowelO, vowelU));

is there a more efficient way to count how many vowels in a string?

It will likely be more efficient using a Counter, then extracting the values for the vowels, and retuen them:

from collections import Counter

def count_vowels(phrase):
""" accepts a string and counts the number of each vowels.
returns a dictionary key --> values
of each vowel and their number of occurrences.
"""
vowels = "aeiou"
frequencies = Counter(phrase.lower())
return {vowel: frequencies[vowel] for vowel in vowels}

as a one-liner:

(as suggested by @stevenRumbalski in the comments)

from collections import Counter

def count_vowels(phrase):
""" accepts a string and counts the number of each vowels.
returns a dictionary key --> values
of each vowel and their number of occurrences.
"""
vowels = "aeiou"
return Counter(c for c in phrase.lower() if c in vowels)


Related Topics



Leave a reply



Submit