Subjects programming

Character Count

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

Search Solutions

Character Count


1. The problem is to create a function that counts how many times each character appears in a given string, ignoring case. 2. The function should accept only alphabetic characters and return an error message if any non-alphabetic characters are found. 3. To start, check if the input string is non-empty and contains only alphabetic characters using Python's `str.isalpha()` method. 4. If the input is valid, convert the entire string to lowercase using `str.lower()` to count characters case-insensitively. 5. Create an empty dictionary to store character counts. 6. Iterate over each character in the lowercase string: - For each character, if it is already in the dictionary, increment its count by 1. - Otherwise, add the character to the dictionary with a count of 1. 7. Return the dictionary containing characters and their counts. 8. If the input string is empty or contains any non-alphabetic characters, return the message: "Input must contain only alphabetic characters."