Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count characters in a string from a list of characters

I'm trying to write a function count(s, chars) that takes a string s and a list of characters chars. The function should count the number of occurrences of the letters given in chars. It should return a dictionary where the keys are the characters given in the list of characters chars.

So for example:

In [1]: s = "Another test string with x and y but no capital h."
In [2]: count(s, ['A', 'a', 'z'])
Out[2]: 'A': 1, 'a': 3, 'z': 0

I made some code that can count all the characters of the string and return a dictionary of it:

return {i: s.count(i) for i in set(s)}

but I'm not sure how you would use a list of specific characters and return a dictionary...

like image 662
Nick Charlton Avatar asked Jan 15 '17 18:01

Nick Charlton


People also ask

How do you count characters in a string in Python?

In Python, you can get the length of a string str (= number of characters) with the built-in function len() .

How do you count occurrences of characters in a string in Java?

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.


1 Answers

What about:

def count_chars(s,chars):
    return {c : s.count(c) for c in chars}

Generates:

$ python3
Python 3.5.2 (default, Nov 17 2016, 17:05:23) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> s = "Another test string with x and y but no capital h."
>>> def count_chars(s,chars):
...     return {c : s.count(c) for c in chars}
... 
>>> count_chars(s, ['A', 'a', 'z'])
{'z': 0, 'A': 1, 'a': 3}

Although this is rather inefficient. Probably a more efficiency way is do the counting in one step. You can use a Counter for this and then retain the interesting characters:

from collections import Counter

def count_chars(s,chars):
    counter = Counter(s)
    return {c : counter.get(c,0) for c in chars}
like image 118
Willem Van Onsem Avatar answered Sep 29 '22 11:09

Willem Van Onsem