[Tutor] Counting number of occurrence of each character in a string

Mark Lawrence breamoreboy at gmail.com
Wed Sep 2 08:19:24 EDT 2020


On 02/09/2020 11:19, Manprit Singh wrote:
> 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
> 

I'd reach straight for the Counter class 
https://docs.python.org/3/library/collections.html#collections.Counter

mark at mark-HP-15-Notebook-PC:~$ python3.8
Python 3.8.3 (default, Jun 23 2020, 00:38:34)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
 >>> from collections import Counter
 >>> a = "ABRACADABRA"
 >>> d = Counter(a)
 >>> d
Counter({'A': 5, 'B': 2, 'R': 2, 'C': 1, 'D': 1})
 >>>


-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence



More information about the Tutor mailing list