Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting each letter's frequency in a string

This is a question from pyschools.

I did get it right, but I'm guessing that there would be a simpler method. Is this the simplest way to do this?

def countLetters(word):
    letterdict={}
    for letter in word:
        letterdict[letter] = 0
    for letter in word:
        letterdict[letter] += 1
    return letterdict

This should look something like this:

>>> countLetters('google')
{'e': 1, 'g': 2, 'l': 1, 'o': 2}
like image 926
Rohit Avatar asked May 29 '12 21:05

Rohit


People also ask

How do you count the frequency of each character in a string in Python?

count() coupled with set() can also achieve this task, in this we just iterate over the set converted string and get the count of each character in original string and assign that element with that value counted using count() .

How do you count the letter frequency in a string in Java?

You can use a java Map and map a char to an int . You can then iterate over the characters in the string and check if they have been added to the map, if they have, you can then increment its value. At the end you will have a count of all the characters you encountered and you can extract their frequencies from that.

How do you count the frequency of each letter in a string C++?

The code snippet for this is given as follows. for(int i = 0; str[i] != '\0'; i++) { if(str[i] == c) count++; } cout<<"Frequency of alphabet "<<c<<" in the string is "<<count; The program to find the frequency of all the alphabets in the string is given as follows.


2 Answers

In 2.7+:

import collections
letters = collections.Counter('google')

Earlier (2.5+, that's ancient by now):

import collections
letters = collections.defaultdict(int)
for letter in word:
    letters[letter] += 1
like image 127
Cat Plus Plus Avatar answered Sep 23 '22 23:09

Cat Plus Plus


>>> import collections
>>> print collections.Counter("google")
Counter({'o': 2, 'g': 2, 'e': 1, 'l': 1})
like image 42
mata Avatar answered Sep 22 '22 23:09

mata