easy +10 pts

Count consonants

Count how many consonant letters appear in a given string.

Implement a function `count_consonants(s: str) -> int` that takes a string `s` and returns the number of consonant letters in it. Consonants are all alphabetic characters that are not vowels. Vowels are the letters 'a', 'e', 'i', 'o', 'u' (case-insensitive). The input string may contain spaces, digits, punctuation, and letters of any case. Only letters count; spaces, digits, punctuation, and other non-letter characters are ignored. For example, the string "Hello, World!" has 7 consonants (H, l, l, W, r, l, d).

Constraints

Input string length is between 0 and 100,000. The function must handle an empty string, strings with no letters, and strings with only vowels. Complexity: O(n) time where n is the length of the string, O(1) extra space.

Example

>>> count_consonants("Hello, World!")
7
>>> count_consonants("AEIOU")
0
>>> count_consonants("")
0
>>> count_consonants("Python is fun")
8
10 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use `char.isalpha()` to check if a character is a letter.
Convert each character to lowercase to handle case insensitivity.
Check if the character is not in the set of vowels.
Use a loop or a generator expression with `sum()`.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.