Subjects programming

Character Counting

Step-by-step solutions with LaTeX - clean, fast, and student-friendly.

Search Solutions

Character Counting


1. **State the problem:** Create a Python function `count_characters(s)` that counts the frequency of each alphabetic character in the input string, ignoring case. The function must accept only non-empty strings of alphabetic characters and return an error message if the input contains any invalid characters. 2. **Input validation:** Check if the input string $s$ is non-empty and contains only letters $A-Z$ or $a-z$. If it contains any non-alphabetic character, return the string: ```Input must contain only alphabetic characters.``` This ensures data integrity and function correctness. 3. **Case-insensitive counting:** Convert the input string to lowercase using: $$ s = s.lower() $$ This treats uppercase and lowercase letters as the same. 4. **Counting characters:** Initialize an empty dictionary to store counts. Iterate through each character in the lowercase string: - If the character is already a key, increment its value by 1. - Otherwise, add the character to the dictionary with a value of 1. 5. **Return the dictionary:** After counting, return the dictionary representing the frequency of each character. **Example:** ```python def count_characters(s): if not s.isalpha(): return "Input must contain only alphabetic characters." s = s.lower() counts = {} for char in s: counts[char] = counts.get(char, 0) + 1 return counts ``` Test with input `DataScience`: ```python count_characters('DataScience') ``` Output: ```{'d': 1, 'a': 2, 't': 1, 's': 1, 'c': 2, 'i': 1, 'e': 2, 'n': 1}``` Test with input `Machine Learning` (contains space): ```python count_characters('Machine Learning') ``` Output: ```Input must contain only alphabetic characters.```