|
| 1 | +""" |
| 2 | +Consonant Count |
| 3 | +Given a string and a target number, determine whether the string contains exactly the target number of consonants. |
| 4 | +
|
| 5 | +Consonants are all alphabetic characters except "a", "e", "i", "o", and "u" in any case. |
| 6 | +Ignore digits, punctuation, spaces, and other non-letter characters when counting. |
| 7 | +""" |
| 8 | + |
| 9 | +import unittest |
| 10 | + |
| 11 | +class ConsonantCountTest(unittest.TestCase): |
| 12 | + |
| 13 | + def test1(self): |
| 14 | + self.assertEqual(has_consonant_count("helloworld", 7), True) |
| 15 | + |
| 16 | + def test2(self): |
| 17 | + self.assertEqual(has_consonant_count("eieio", 5), False) |
| 18 | + |
| 19 | + def test3(self): |
| 20 | + self.assertEqual(has_consonant_count("freeCodeCamp Rocks!", 11), True) |
| 21 | + |
| 22 | + def test4(self): |
| 23 | + self.assertEqual(has_consonant_count("Th3 Qu!ck Br0wn F0x Jump5 0ver Th3 L@zy D0g.", 24), False) |
| 24 | + |
| 25 | + def test5(self): |
| 26 | + self.assertEqual(has_consonant_count("Th3 Qu!ck Br0wn F0x Jump5 0ver Th3 L@zy D0g.", 23), True) |
| 27 | + |
| 28 | + |
| 29 | + |
| 30 | +def has_consonant_count(text, target): |
| 31 | + |
| 32 | + consonant_count = 0 |
| 33 | + |
| 34 | + for char in text: |
| 35 | + if char.isalpha(): |
| 36 | + if char.lower() not in "aeiou": |
| 37 | + consonant_count += 1 |
| 38 | + return consonant_count == target |
| 39 | + |
| 40 | + |
| 41 | +def has_consonant_count(text, target): |
| 42 | + |
| 43 | + vowels = set("aeiouAEIOU") |
| 44 | + consonant_count = 0 |
| 45 | + |
| 46 | + for char in text: |
| 47 | + if char.isalpha() and char not in vowels: |
| 48 | + consonant_count += 1 |
| 49 | + |
| 50 | + |
| 51 | + return consonant_count == target |
| 52 | + |
| 53 | + |
| 54 | + |
| 55 | +if __name__ == "__main__": |
| 56 | + print(has_consonant_count("Hi hello world ",8)) |
| 57 | + unittest.main() |
0 commit comments