Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting vowels in an array

I know I'm close to figuring this out but I've been wracking my brain and can't think of what's going wrong here. I need to count the number of vowels in the array of nameList using the vowelList array, and currently it's outputting 22, which is not the correct number of vowels.

Incidentally, 22 is double the length of the array nameList, but I can't see any reason what I wrote would be outputting double the array length. Any help would be appreciated. Not looking for the answer, for a nudge in the right direction.

nameList = [ "Euclid", "Archimedes", "Newton","Descartes", "Fermat", "Turing", "Euler", "Einstein", "Boole", "Fibonacci", "Nash"]
vowelList = ['A', 'a', 'E', 'e', 'I', 'i', 'O', 'o', 'U','u']

z=0
counter = 0
for k in nameList:
    i = 0
    for q in vowelList:
        counter+=nameList[z].count(vowelList[i])
        i+=1
    z=+1
print("The number of vowels in the list is",counter)
like image 901
wombatpandaa Avatar asked Oct 16 '20 23:10

wombatpandaa


2 Answers

You're thinking about this too hard. Relax and let Python do the work:

nameList = [ "Euclid", "Archimedes", "Newton","Descartes", "Fermat", "Turing", "Euler", "Einstein", "Boole", "Fibonacci", "Nash"]
nameStr = ''.join(nameList).lower()
nVowels = len([c for c in nameStr if c in 'aeiou'])
print(f"The number of vowels in the list is {nVowels}.")
>>> The number of vowels in the list is 31.

Plenty of ways to skin a cat in Python :)

like image 58
Rohan S Byrne Avatar answered Sep 28 '22 06:09

Rohan S Byrne


Here's something more comprehensible:

nameList = [ "Euclid", "Archimedes", "Newton","Descartes", "Fermat", "Turing", "Euler", "Einstein", "Boole", "Fibonacci", "Nash"]
vowelList = ['A', 'a', 'E', 'e', 'I', 'i', 'O', 'o', 'U','u']


counter = 0
for name in nameList:
    for char in name:
        for vowel in vowelList:
            if char == vowel:
                counter += 1
print("The number of vowels in the list is",counter)

The number of vowels in the list is 31

like image 23
Stab Avatar answered Sep 28 '22 05:09

Stab