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')
Solution 1:
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).
Solution 2:
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}
Post a Comment for "Python - Letter Count Dict"