Write a function, countChar(STRING), that takes a string as an argument and returns a dictionary containing the frequency of each character in the string.
For example, if the string is "Hello world", the output will be
{'H': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}
Answer:
Answer by student
Detailed answer by teachoo
-lock-
-
The function countChar(STRING) in Python takes a string as an argument and returns a dictionary containing the frequency of each character in the string. To write this function, we need to follow these steps:
- Initialize an empty dictionary freq. This dictionary will store the characters as keys and their frequencies as values.
- Loop through the characters of the string STRING using a for loop . For each character , assign it to a variable char .
- Check if the char is already in the freq dictionary using the in operator . If yes, increment its value by one using the += operator. If no, add a new key-value pair to the freq dictionary with the char as the key and 1 as the value using the assignment operator (=).
- After the loop, return the freq dictionary using the return statement.
- The code for this function is:
-endlock-