'Python code to count vowels

Assume s is a string of lower case characters.

Write a program that counts up the number of vowels contained in the string s. Valid vowels are: 'a', 'e', 'i', 'o', and 'u'. For example, if s = 'azcbobobegghakl', your program should print:

Number of vowels: 5

I have this so far

count = 0
vowels = 'a' or 'e' or 'i' or 'o' or 'u'
    for vowels in s:
        count +=1
print ('Number of vowels: ' + count)

Can anyone tell me what is wrong with it?



Solution 1:[1]

A couple of problems. First, your assignment to vowels doesn't do what you think it does:

>>> vowels = 'a' or 'e' or 'i' or 'o' or 'u'
>>> vowels
'a'

Python evaluates or lazily; as soon as any of the predicates evaluates True it is returned. Non-empty sequences, including strings other than "" evaluate True, so 'a' is returned straight away.

Second, when you iterate over s, you ignore that assignment anyway:

>>> for vowels in "foo":
    print(vowels)


f
o
o

for x in y: assigns each item in the iterable y to the name x in turn, so anything previously assigned to x is not longer accessible via that name.

I think what you want is:

count = 0
vowels = set("aeiou")
for letter in s:
    if letter in vowels:
        count += 1

Solution 2:[2]

As a start, try this:

In [9]: V = ['a','e','i','o','u']

In [10]: s = 'azcbobobegghakl'

In [11]: sum([1 for i in s if i in V])
Out[11]: 5

Solution 3:[3]

Using your own loop.

count = 0
vowels = ['a' , 'e' , 'i' ,'o' , 'u']
for char in s:
    if char in vowels: # check if each char in your string is in your list of vowels
        count += 1
print ('Number of vowels: ' + str(count)) # count is an integer so you need to cast it as a str

You can use string formatting also:

print ('Number of vowels: {} '.format(count))

Solution 4:[4]

x = len(s)        
a = 0        
c = 0        
while (a < x):        
    if s[a] == 'a' or s[a] == 'e' or s[a] == 'i' or s[a] == 'o' or s[a] == 'u':        
        c += 1        
    a = a+1        
print "Number of vowels: " + str(c)

The above code is for beginners

Solution 5:[5]

here is the simple one:

count = 0    #initialize the count variable

def count_vowel(word):    #define a function for counting the vowels
    vowels = 'aeiouAEIOU'    #A string containing all the vowels
    for i in range(word):    #traverse the string
        if i in vowels:    #check if the the character is contained in the vowel string
            count = count + 1    #update the count
return count

Solution 6:[6]

//Using while loop:- 
%%time
s = 'services'
m = list(s)
count = 0
while m:
    d = m.pop()
    if (d is 'a') or (d is 'e') or (d is 'i') or (d is 'o') or (d is 'u'):
        count += 1

Result is :- CPU times: user 0 ns, sys: 0 ns, total: 0 ns Wall time: 18.8 µs // using for loop one line:-

%%time
vowels = ['a', 'e', 'i', 'o', 'u']
sum([s.count(elem) for elem in vowels])

Result is :- CPU times: user 0 ns, sys: 0 ns, total: 0 ns Wall time: 18.6 µs

Solution 7:[7]

This is also another solution,

In [12]: vowels = ['a', 'e', 'i', 'o', 'u']

In [13]: str = "azcbobobegghakl"

In [14]: sum([str.count(elem) for elem in vowels])
Out[14]: 5

Using string.count()

Solution 8:[8]

Here is a sample that uses Counter and is more compact and even a little faster than Sundar's for larger strings:

from collections import Counter 
cnt = Counter('this and that')
sum([cnt[x] for x in 'aeiou'])

Here is a time test to compare 3 approaches:

import time
from collections import Counter 
s = 'That that is is is not that that is not is not.  This is the understanding of all who begin to think.'
c = Counter(s)
dt1 = dt2 = dt3 = dt4 = 0; 
vowels = ['a' , 'e' , 'i' ,'o' , 'u']
for i in range(100000):
    ms0 = time.time()*1000.0
    s1 = sum([c[x] for x in 'aeiou'])
    ms1 = time.time()*1000.0
    dt1 += ms1 - ms0
for i in range(100000):
    ms1 = time.time()*1000.0
    s2 = sum([c[x] for x in set(vowels).intersection(c.keys())])
    ms2 = time.time()*1000.0
    dt2 += ms2 - ms1
for i in range(100000):
    ms2 = time.time()*1000.0
    s3 = 0
    for char in s:
        if char in vowels: # check if each char in your string is in your list of vowels
            s3 += 1
    ms3 = time.time()*1000.0
    dt3 += ms3 - ms2
print('sums:', s1, s2, s3)
print('times:', dt1, dt2, dt3)
print('relative:  {:.0%}{:.0%}{:.0%}'.format(dt1/dt2, dt2/dt2, dt3/dt2))

Results (average of six runs), versions: this, Sundar, simple sums: 26 26 26 times: 392 494 2626
relative: 80% 100% 532%

Solution 9:[9]

My solution:

s = 'aassfgia'
vowels = 0
for x in s:
    if x == 'a' or x == 'e' or x == 'i' or x == 'o' or x == 'u':
        vowels += 1
        print x
print vowels

Solution 10:[10]

For counting vowels from string

s = "Some string here" 

or

s = intput(raw_input("Enter ur string"))

s1 = s.lower()
count = 0
vowels = set("aeiou")
for letter in s1:
  if letter in vowels:
    count += 1
print 'Number of vowels:' ,count

this will give u output for total count of vowels in given string

Solution 11:[11]

total = 0
for c in s:
    if c == 'a' or c == 'e' or c == 'i' or c == 'o' or c == 'u':
        total += 1
print "Number of vowels: " + str(total)

ALTERNATE SOLUTION

num = 0
for letter in s:
  if letter in "aeiou":
    num+=1
print "Number of vowels:" + str(num)

Solution 12:[12]

count=0
for letter in s:

    if(letter=='a' or letter == 'e' or letter =='i' or letter =='o' or letter=='u'):
         count=count+1

print("Number of vowels:",count)

Solution 13:[13]

strings = raw_input('Enter a string: ')

vowels = 0

for char in strings:
    if(char ==('a') or char ==('e') or char ==('i') or char ==('o') or char ==('u')):
        vowels += 1

print('Number of vowels: ' + str(vowels))

Solution 14:[14]

You need an array. That is a sequence of element, in your case characters. Here is a way to define an array in Python:

vowels  = ['a','e','i','o','u']

Solution 15:[15]

Here's a simple solution making use of an in operator and a for loop:

s = 'azcbobobegghakl'

count = 0
for i in s.lower():
    if i in "aeiou":
        count += 1
print(count)

Why s.lower()? To make it work with any string containing vowels in capitals.

Solution 16:[16]

str = 'aeioubbaeiouggaeiouss'
vow = set("aeiouAEIOU")
count = 0

for alpha in str:
    if alpha in vow:
        count += 1
print(count)

Count will give total number of times vowels came in string.

Solution 17:[17]

for i in s:
    if i in vowels:
        num_vowels += 1
print (num_vowels)

Solution 18:[18]

you can you this code to find count

  mystr='hello world'
    
  count= sum(1 if c.lower() in 'aeiou' else 0 for c in mystr) 

   #output:3

Solution 19:[19]

inputstring =input("Enter a string")
vowels = "aeiuoAEIOU"
print(len([letter for letter in inputstring if letter in vowels]))
print([letter for letter in inputstring if letter in vowels])

This should allow to get the count and show the vowels in a string inputted or supplied

Solution 20:[20]

A different implementation using counter

from collections import Counter
s='azcbobobegghakl'
vowels="aeiou"
c=Counter(s)
print sum([c[i] for i in set(vowels).intersection(c.keys())])

the statement set(vowels).intersection(c.keys()) this returns the dictint vowels present in the sentence

Solution 21:[21]

print("\nThe count of vowels are:",sum([1 for i in input("\nEnter the string\n\n").lower() if i in ['a','e','i','o','u']]),"\n")

Enter the string

azcbobobegghakl

The count of vowels are: 5

print("\nThe count of vowels are:",sum([1 for i in input("\nEnter the string\n\n").lower() if i in ['a','e','i','o','u']]),"\n")

Enter the string

azCBOBOBegghakl

The count of vowels are: 5