-1

I have written a basic code to count the number of vowels in a given string using a for loop. I am wondering if there is a more elegant way of writing the code?

The code which works:

words = input(str("Enter a word:")) #String input from user
words_list = list(words) #Convert user input to a list
vowels = ["a", "e", "i", "o", "u"] #Define vowels list
number = 0 #No: of vowels set to 0
for word in words_list: 
    if word in vowels: 
        number += 1 
print(f"The number of vowels in {words} are {number}")
moonpie
  • 1
  • 1

2 Answers2

0

fastest code for most strings

sum(map(mystring.lower().count, 'aeiou'))

Using high performance numpy operations is faster for very large strings

import numpy as np
words = input(str("Enter a word:"))
mystringarray = np.frombuffer(words.lower().encode('ascii', 'ignore'), dtype=np.uint8)
vowels = np.frombuffer("aeiou".encode('ascii'), dtype=np.uint8)
count = np.isin(mystringarray, vowels).sum()

using list a list comprehension (instead of a generator) with an if statement after instead of summing true and false is slightly faster, but still slower than using map count

vowels = set('aeiou')
count = sum([1 for c in words.lower() if c in vowels])

benchmarks for anyone interested

arrmansa
  • 518
  • 10
  • 2
    This *may* be more efficient for very large strings but otherwise it's incredibly slow – DarkKnight Feb 25 '23 at 07:34
  • the break even is ~300 chars. for 20,000 chars it's 100us vs 2ms, so 20 times faster. – arrmansa Feb 25 '23 at 07:51
  • When compared to the regular expression solution (see link to duplicate question) the break-even point is with a string length of ~4700 when tested on Python 3.11.2, macOS 13.2.1, 32GB RAM, 3 GHz 10-Core Intel Xeon W – DarkKnight Feb 25 '23 at 08:15
-1

I suppose you could use regex, and do:

import re
words = input("Enter a word: ")
number = len(re.findall("[aeiou]", words))

print(f"The number of vowels in {words} are {number}")
sbottingota
  • 533
  • 1
  • 3
  • 18