Letter counting¶
Save the following functions into a file named letters.py.
Write the function
occurrences()that takes a text (str), and returns a dictionary (dict) where the key is a lowercase letter or a digit and the value is the number of occurrences of it in the given text. Letters in the given text may be upper or lowercase. This dictionary will not contain any letter that does not appear in the given string, i. e., we must build an incomplete dictionary.See the following examples:
>>> d = occurrences('Genius is 1% inspiration and 99% perspiration. Thomas Edison.') >>> if d != {'g': 1, 'e': 3, 'n': 6, 'i': 8, 'u': 1, 's': 6, '1': 1, 'p': 3, ... 'r': 3, 'a': 4, 't': 3, 'o': 4, 'd': 2, '9': 2, 'h': 1, 'm': 1}: ... print(d) >>> d = occurrences("I'm gonna make him an offer he can't refuse. Vito Corleone.") >>> if d != {'i': 3, 'm': 3, 'g': 1, 'o': 5, 'n': 5, 'a': 4, 'k': 1, 'e': 7, ... 'h': 2, 'f': 3, 'r': 3, 'c': 2, 't': 2, 'u': 1, 's': 1, 'v': 1, 'l': 1}: ... print(d)
Note
More tests are provided in file
test-occurrences.txt.Write the function
vowel_occurrences()that takes a text (str), and returns a dictionary (dict) where the key is a lowercase vowel and the value is the number of occurrences of it in the given text. Letters in the given text may be upper or lowercase. This dictionary will contain all five vowels regardless of wether they are in the text or not, i. e., the dictionary must be complete.See the following examples:
>>> d = vowel_occurrences('Genius is 1% inspiration and 99% perspiration. Thomas Edison.') >>> if d != {'a': 4, 'e': 3, 'i': 8, 'o': 4, 'u': 1}: ... print(d) >>> d = vowel_occurrences('Three can keep a secret, if two of them are dead. Benjamin Franklin') >>> if d != {'a': 6, 'e': 10, 'i': 3, 'o': 2, 'u': 0}: ... print(d)
Note
More tests are provided in file test-vowel_occurrences.txt.
Solution
A solution of these functions is provided in file letters.py