Reputation: 19
The code I currently have requires me to input all the vowels or consonants, I don't think this is very efficient. As of now, I'm not allowed to use map
or for
in my code because I'm on chapter 2 of python (this covers lists, slicing..)
phrase = input("Phrase: ")
num_words = len(phrase.split(" "))
num_vowels = (
phrase.count("a")
+ phrase.count("e")
+ phrase.count("i")
+ phrase.count("o")
+ phrase.count("u")
)
num_consonants = len(phrase.replace(" ", "")) - num_vowels
num_char = len(phrase)
print(f"words: {num_words}")
print(f"vowels : {num_vowels}")
print(f"consonants: {num_consonants}")
print(f"chars: {num_char}")
I'm wondering if there's an optimized way of accomplishing this on the level I currently am at programming.
Upvotes: 1
Views: 113
Reputation: 68
I agree with all the comments - your code is fine. But I also hear you, you didn't get into python to manually write phrase.count() five times! python is supposed to be simple and concise even at a starting level.
A suggestion of an alternate way you could do the same thing would be list comprehension:
num_vowels = sum([phrase.count(each_vowel) for each_vowel in 'aeiou'])
Now I don't know if that is cheating (there is a "for" loop fairly prominent inside the list comprehension) - maybe one of the many, many more experienced programmers could comment. But if you are starting I really recommend you spend some time learning the tricks to list comprehension - it goes a long way making your code more concise.
Upvotes: 1
Reputation: 96
If you're allowed to use packages, re will do the trick:
import re
num_vowels = len(re.findall('[aeiouAEIOU]+', phrase))
If you're only allowed to use base python, then this is a barely cleaner (but functionally not different) way to print:
print("words: " + str(num_words),'\n' + "vowels: " + str(num_vowels), "\n" + "consonants: " + str(num_consonants), '\n' + "chars: " + str(num_char))
Hope this helps!
Upvotes: 0