Reputation: 45
I'm trying to create a tool that analyses the word that the user types. It accounts for the number of letters (done), the number of vowels (need help), the number of capital letters (done) and also the most common letter (not worried yet). I have done the following code:
word = raw_input("Please enter a word:")
print word
if len(word) == 1:
print word + " has " + str(len(word)) + " letter."
else:
print word + " has " + str(len(word)) + " letters."
if sum(1 for v in word if v ==["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]) == 1:
print "It also has ", sum(1 for v in word if v == ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]), " vowel."
else:
print "It also has ", sum(1 for v in word if v == ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]), " vowels."
if sum(1 for c in word if c.isupper()) == 1:
print "It has ", sum(1 for c in word if c.isupper()), " capital letter."
else:
print "It has ", sum(1 for c in word if c.isupper()), " capital letters."
Using the word 'HeLLo' for example, it returns the following:
HeLLo
HeLLo has 5 letters.
It also has 0 vowels.
It has 3 capital letters.
I'm confused because it knows to count the number of vowels and include it in the answer, yet doesn't count the vowels in the word.
Do I need to make a small adjustment or a large change?
Thanks.
P.S. How do I mark a question as answered?
Upvotes: 0
Views: 389
Reputation: 82889
You are comparing the letter to a list. Instead, check whether that letter is in
that list.
sum(1 for v in word if v in ["a", more vowels, "U"])
Also, you can make your code somewhat shorter by using a string instead of a list, and by lower-casing the letter first, and by not repeating yourself as much.
num_vowels = sum(1 for v in word if v.lower() in "aeiou")
print "It also has ", num_vowels, (" vowel." if num_vowels == 1 else " vowels.")
For finding the most common letter, you should use a dictionary. Just iterate the letters in the word and increase their count in the dict, then pick the one with highest count.
counts = {}
for x in word:
counts[x] = counts.get(x, 0) + 1
print "most common:", max(word, key=lambda x: counts[x])
Or just use collections.Counter(word).most_common(1)
Upvotes: 2