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}
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() .
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.
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.
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
>>> import collections
>>> print collections.Counter("google")
Counter({'o': 2, 'g': 2, 'e': 1, 'l': 1})
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