pythonedx

How to make a function checking how many consonants or vowels are in a string?


I'm doing Georgia Tech's CS1301xII course, and I have been stumped by this question. I am supposed to make a function called count_letters. If find_consonants is true, then it counts consonants, or vowels if it is false. It should only return vowels and consonants, no uppercase letters, spaces, numbers, or punctuation. The output I get is 0 consonants, then 1 vowel. I expected 14, then 7.

def count_letters(string, find_consonants):
    if find_consonants == True:
        count = 0
        for i in string:
            if i == ("q" or "w" or"r" or "t" or "y" or "p" or "s" or "d" or "f" or "g" or "h" or "j" or "k" or "l" or "z" or "x" or "c" or "v" or "b" or "n" or "m"):
                count += 1
        return count
    else:
        count = 0
        for i in string:
            if i == ("a" or "e" or "i" or "o" or "u"):
                count += 1
        return count

(The next section is just for me to test myself, the autograder changes the string) a_string = "up with the white and gold"

print(count_letters(a_string, True))
print(count_letters(a_string, False))

Solution

  • The test if find_consonants == True is a bit overengineered. if find_consonants suffices. You might also want to make use of list comprehensions, to avoid the explicit loops.

    This should work for instance:

    def count_letters(s, find_consonants):
        if find_consonants:
            return len([l for l in s if l in "bcdfghjklmnpqrstvwxyz"])
        return len([l for l in s if l in "aeiou"])