Reputation: 45
How do I apply a for loop to a string in Python which allows me to count each letter in a word? The ultimate goal is to discover the most common letter.
This is the code so far:
print "Type 'exit' at any time to exit the program."
continue_running = True
while continue_running:
word = raw_input("Please enter a word: ")
if word == "exit":
continue_running = False
else:
while not word.isalpha():
word = raw_input("ERROR: Please type a single word containing alphabetic characters only:")
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.upper() if v in ["A", "E", "I", "O", "U"]) == 1:
print "It also has ", sum(1 for v in word.upper() if v in ["A", "E", "I", "O", "U"]), " vowel."
else:
print "It also has ", sum(1 for v in word.upper() if v in ["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."
for loop in word:
I know I can use the:
(collections.Counter(word.upper()).most_common(1)[0])
format, but this isn't the way I want to do it.
Upvotes: 1
Views: 293
Reputation: 1121416
You can simply loop directly over strings; they are sequences just like lists and tuples; each character in the string is a separate element:
for character in word.upper():
# count the character.
Counts can then be collected in a dictionary:
counts = {}
for character in word.upper():
# count the character.
counts[character] = counts.get(character, 0) + 1
after which you'd pick the most common one; you can use the max()
function for that:
most_common = max(counts, key=counts.__getitem__) # maximum by value
Demo:
>>> word = 'fooBARbazaar'
>>> counts = {}
>>> for character in word.upper():
... # count the character.
... counts[character] = counts.get(character, 0) + 1
...
>>> counts
{'A': 4, 'B': 2, 'F': 1, 'O': 2, 'R': 2, 'Z': 1}
>>> max(counts, key=counts.__getitem__)
'A'
Upvotes: 3
Reputation: 1508
If you don't want to re-invent the wheel try using Counter
>>> from collections import Counter
>>> x = Counter("stackoverflow")
>>> x
Counter({'o': 2, 'a': 1, 'c': 1, 'e': 1, 'f': 1, 'k': 1, 'l': 1, 's': 1, 'r': 1, 't': 1, 'w': 1, 'v': 1})
>>> print max(x, key=x.__getitem__)
o
>>>
Upvotes: 0