makavelllli
makavelllli

Reputation: 1

Use loops more efficiently

I am looking to write a program where I enter a word or a phrase and it counts the number of vowels in the input and then returns how many of each vowel there is. I have done this, but my code is very long and I want to know how I can write it more efficiently.

How can I reduce the amount of for loops I use?

text = input("enter string:")

vowels = ["a","e","i","o","u"]
count = 0
for letters in text:
    if letters in vowels:
        count = count + 1


print ("vowel count is:",count)
numA = 0
numE = 0
numI = 0
numO = 0
numU = 0

for a in text:
    if a in "a":
        numA = numA + 1

for e in text:
    if e in "e":
        numE = numE + 1

for i in text:
    if i in "i":
        numI = numI + 1

for o in text:
    if o in "o":
        numO = numO + 1

for u in text:
    if u in "u":
        numU = numU + 1




print ("a occurs",numA)
print ("e occurs",numE)
print ("i occurs",numI)
print ("o occurs",numO)
print ("u occurs",numU)

Upvotes: 0

Views: 131

Answers (5)

boardrider
boardrider

Reputation: 6185

Trying to preserve your original code as much as possible, here's your algorithm, using a dict - to count vowels:

#text = input("enter string:")
text = "phraseanditcountsthenumberofvowels"

vowels = {"a":0,"e":0,"i":0,"o":0,"u":0}
for letter in text:
    letter = letter.lower()
    if letter in vowels:
        vowels[letter] += 1

print(vowels)

Upvotes: 0

Guillaume
Guillaume

Reputation: 6009

In complement to @Lutz Horn answer, you can make it much shorter, and also count the number of different vowels, as you need:

text = input("enter string:")
# counts the number of different vowels
no_vowels = len(set(text).intersection("aeiou"))
# this is a dict comprehension, it constructs a dict with a vowel as key and the occurrence count as key
counts = {vowel: text.count(vowel) for vowel in "aeiou"}

# then you can print the number of occurrences from each item
print("vowel count is:", no_vowels)
for vowel in "aeiou":
    print(vowel, "is used", count[vowel], "times")

Or you can reduce that to 4 readable lines, if you don't need to keep the counts in a variable, but just need to print them:

text = input("enter string:")
print("vowel count is", len(set(text).intersection("aeiou")))
for vowel in "aeiou":
     print(vowel, "occurs", text.count(vowel), "times")

Or you could use Python built-in collections.Counter which offers both best performance and functionalities:

from collections import Counter
text = input("enter string:")
counter = Counter(text)

# counter now contains the counts for all letters, not only vowels
for vowel in "aeiou":
    print(vowel, "occurs", counter[vowel], "times")

# this one is trickier, it is a sum of boolean, which returns the number of True
print("vowel count is:", sum(vowel in counter for vowel in "aeiou"))

Upvotes: 1

Skrunch
Skrunch

Reputation: 1

I like the dictionary example shown above but if you want a slight change you could do the following:

  1. Only iterate over the input string once.
  2. Use an array track the count for each vowel.

    vowelArray = [0, 0, 0, 0, 0]
    inputStr = "This is the string to loop over"
    
    for char in inputStr:
        if char == "a":
            vowelArray[0] += 1
        if char == "e":
            vowelArray[1] += 1
        if char == "i":
            vowelArray[2] += 1
        if char == "o":
            vowelArray[3] += 1
        if char == "u":
            vowelArray[4] += 1
    
    print(vowelArray)
    

Upvotes: 0

Huy Vo
Huy Vo

Reputation: 2500

You can use count():

number_of_a = text.count('a')
number_of_e = text.count('e')
...

and for the total number of vowels:

number_of_vowels = sum(1 for x in text if x in 'aeiou')

Upvotes: 0

user6999902
user6999902

Reputation:

Use a dict:

vowels = ["a", "e", "i", "o", "u"]
# We use a dict to count the vowels.
# It is initialized with 0 for every vowel.
count = {v: 0 for v in vowels}

# Loop over every character in the input.
for c in "foo bar baz":
    # If the character is a vowel, increment its count.
    if c in vowels:
        count[c] = count[c] + 1

print(count)

Output:

{'i': 0, 'u': 0, 'a': 2, 'o': 2, 'e': 0}

Upvotes: 6

Related Questions