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

[Class 12] Write a function, countChar(STRING), that takes a string - Teachoo Sample Paper - Computer Science Class 12

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:

part 2 - Question 21 (Choice 2) - Teachoo Sample Paper - Computer Science Class 12 - Solutions to CBSE Sample Paper - Computer Science Class 12 - Computer Science - Class 12

-endlock-

Remove Ads
Teachoo · Class 12 Explore Class 12
Davneet Singh's photo - Co-founder, Teachoo

Made by

Davneet Singh

Davneet Singh is an IIT Kanpur graduate and has been teaching for 16+ years. At Teachoo, he breaks down Maths, Science and Computer Science into simple steps so students understand concepts deeply and score with confidence.

Many students prefer Teachoo Black for a smooth, ad-free learning experience.