In: Computer Science
Write the function letter_frequencies(text) that returns a dictionary containing all of the letter frequencies of all letters occurring in the parameter text.
For example:
if __name__ == '__main__': d = letter_frequencies('hello, world') print(d) # show the contents of this dictionary
will produce the following output:
{'a': 0.0, 'b': 0.0, 'c': 0.0, 'd': 0.1, 'e': 0.1, 'f': 0.0, 'g': 0.0, 'h': 0.1, 'i': 0.0, 'j': 0.0, 'k': 0.0, 'l': 0.3, 'm': 0.0, 'n': 0.0, 'o': 0.2, 'p': 0.0, 'q': 0.0,'r': 0.1, 's': 0.0, 't': 0.0, 'u': 0.0, 'v': 0.0,'w': 0.1, 'x': 0.0, 'y': 0.0, 'z': 0.0}
The code for given problem statement:
def letter_frequencies(text): # definition of the function
text=text.lower() # Converts all the letters in lowercase
finaltext='' # new text
for i in text: # removes all the characters other than letters
if i.isalpha():
finaltext+=i
alphabet=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] # List of letters
d={} # Dictionary to strore results
for i in alphabet: # Initiallizes the dictionary with all the keys.
d[i]=0.0 # All values are Initiallized by 0.0
for letter in finaltext: # For every letter in the text
d[letter]+=1/len(finaltext) # increaments the value by 0.1
d[letter]=round(d[letter],1) # To eliminate error
return d # returns updated dictionary
if __name__ == '__main__':
print(letter_frequencies('hello, world')) # Calls the function
Screenshot of the code:
Screenshot of output:
Logic of the code:
The code finds the relative frequency for given text
In 'hello, world' there are 10 characters which are letters: h,e,l,l,o,w,o,r,l,d
As frequency of h is 1, the relative frequency = 1/10=0.1
e=1, 1/10=0.1
l=3, 3/10=0.3
o=2, 2/10=0.2
w=1, 1/10=0.1
r=1, 1/10=0.1
d=1, 1/10=0.1
relative frequency=frequency/ total number of elements
The code first lowers all the letters in the text. Copies all the present letters In a new string named finaltext
There is a list defined 'alphabet' in which all the letters are listed.
One dictionary is defined whose keys are all alphabet and values are initialized to 0.0
Then to record frequency a loop is performed for every character in finaltext.
For every letter in text frequency is increased by 1/(total number of letters)
The float value should be updated as there can be little error in float value. For example if this program is executed without rounding off then frequency of 'l' given by code is:
'l': 0.30000000000000004 instead of 0.3
Note that round function rounds the given number upto mentioned decimal places, in this case code is rounding off the number upto 1 decimal place.
Executing this code for some other inputs:
Here input is Python
python word has all 6 different letters
So frequency of p=y=t=h=o=n = 1/6 = 0.167 (rounding off upto 3 decimal place)