[Tutor] Counting number of occurrence of each character in a string
Manprit Singh
manpritsinghece at gmail.com
Wed Sep 2 06:19:40 EDT 2020
Dear sir ,
consider a problem of Counting number of occurrence of each character in a
string
x = "ABRACADABRA"
in this string x :
Number of occurrence of character A = 5
Number of occurrence of character B = 2
Number of occurrence of character R = 2
Number of occurrence of character C = 1
Number of occurrence of character D = 5
The code will be written like this :
>>> a = "ABRACADABRA"
>>> d = {}
>>> for i in a:
d[i] = d.get(i, 0) + 1
will result in
>>> d
{'A': 5, 'B': 2, 'R': 2, 'C': 1, 'D': 1}
Here keys are characters in the string a, and the values are the counts.
in an another way the same result can be achieved by replacing d[i] =
d.get(i, 0) + 1 with dict .update () method,as the code written below :
a = "ABRACADABRA"
>>> d = {}
>>> for i in a:
d.update({i : d.get(i, 0) + 1})
The result again is
>>> d
{'A': 5, 'B': 2, 'R': 2, 'C': 1, 'D': 1}
So in this situation which way should be adopted, :
1) The code with d[i] = d.get(i, 0) + 1 inside for loop
OR
2) The code with d.update({i : d.get(i, 0) + 1})
Regards
Manprit Singh
More information about the Tutor
mailing list