python - Letter Count Dict
Write a Python function called LetterCount()
which takes a string as an argument and returns a dictionary of letter counts.
The line:
print LetterCount("Abracadabra, Monsignor")
Should produce the output:
{'a': 5, 'c': 1, 'b': 2, 'd': 1, 'g': 1, 'i': 1, 'm': 1, 'o': 2, 'n': 2, 's': 1, 'r': 3}
I tried:
import collections
c = collections.Counter('Abracadabra, Monsignor')
print c
print list(c.elements())
the answer I am getting looks like this
{'a': 4, 'r': 3, 'b': 2, 'o': 2, 'n': 2, 'A': 1, 'c: 1, 'd': 1, 'g': 1, ' ':1, 'i':1, 'M':1 ',':1's': 1, }
['A', 'a','a','a','a','c','b','b','d','g', and so on
okay now with this code import collections c = collections.Counter('Abracadabra, Monsignor'.lower())
print c am getting this {'a': 5, 'r': 3, 'b': 2, '开发者_运维问答o': 2, 'n': 2, 'c: 1, 'd': 1, 'g': 1, ' ':1, 'i':1, ',':1's': 1, }
but answer should be this {'a': 5, 'c': 1, 'b': 2, 'd': 1, 'g': 1, 'i': 1, 'm': 1, 'o': 2, 'n': 2, 's': 1, 'r': 3}
You are close. Note that in the task description, the case of the letters is not taken into account. They want {'a': 5}
, where you have {'a': 4, 'A': 1}
.
So you have to convert the string to lower case first (I'm sure you will find out how).
Use dictionary for the letter count:
s = "string is an immutable object"
d = {}
for i in s:
d[i] = d.get(i,0)+1
print d
Output:
{'a': 2, ' ': 4, 'c': 1, 'b': 2, 'e': 2, 'g': 1, 'i': 3, 'j': 1, 'm': 2, 'l': 1, 'o': 1, 'n': 2, 's': 2, 'r': 1, 'u': 1, 't': 3}
Maybe this to count just letters, exclude spaces and overlook its case and sort them alphabetically?:
t = "The cat is out of the bag."
word_count = {}
for i in t.casefold():
if i.isalnum():
word_count[i] = word_count.get(i,0)+1
for letter, count in sorted(word_count.items()):
print(letter, count)
Output: a 2 b 1 c 1 e 2 f 1 g 1 h 2 i 1 o 2 s 1 t 4 u 1
精彩评论