Given the string:
a='dqdwqfwqfggqwq'
How do I get the number of occurrences of each character?
Initialize a counter variable to store the count of total occurrences of a character in a string. Traverse the string character by character. If the character of the string matches with the given character, increment the value of the count variable. Finally, return the counter variable.
In order to find occurence of each character in a string we can use Map utility of Java.In Map a key could not be duplicate so make each character of string as key of Map and provide initial value corresponding to each key as 1 if this character does not inserted in map before.
count() One of the built-in ways in which you can use Python to count the number of occurrences in a string is using the built-in string . count() method. The method takes one argument, either a character or a substring, and returns the number of times that character exists in the string associated with the method.
In 2.7 and 3.1 there's a tool called Counter:
>>> import collections
>>> results = collections.Counter("dqdwqfwqfggqwq")
>>> results
Counter({'q': 5, 'w': 3, 'g': 2, 'd': 2, 'f': 2})
Docs. As pointed out in the comments it is not compatible with 2.6 or lower, but it's backported.
Not highly efficient, but it is one-line...
In [24]: a='dqdwqfwqfggqwq'
In [25]: dict((letter,a.count(letter)) for letter in set(a))
Out[25]: {'d': 2, 'f': 2, 'g': 2, 'q': 5, 'w': 3}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With