TransWikia.com

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

Stack Overflow Asked on November 22, 2021

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))

4 Answers

The or operation in python is lazy evaluation, like:

>>> ('a' or 'c')
'a'
>>> ('c' or 'b' or 'a')
'c'

so i == ("a" or "e" or "i" or "o" or "u") equivalent to i == 'a', is not the result you want.

You can change it like

Option1

This is crazy...though

count = 0
for i in string:
    if (i == "a") or (i == "e") or (i == "i") or (i == "o") or (i == "u"):
        count += 1

Option2

This one is more elegant.

count = 0
for i in string:
    if i in 'aeiou':
        count += 1

Option3

And this is Python

len([x for x in string if x in 'aeiou'])

Answered by K. Prot on November 22, 2021

@ObseleteAwareProduce's solution is correct and addresses the concept of checking if an item matches any item in a specific list. But as far as finding vowels and consonants, we can use re library as well

import re

regex = re.compile("a|e|i|o|u", flags=re.I)
vowels_count = len(regex.finditer(input_string))

Answered by vestronge on November 22, 2021

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"])

Answered by karlson on November 22, 2021

Sadly, you can't use if var == "foo" or "bar"; you'd have to write if var == "foo" or var == "bar". For your function, try something like:

def count(string, count_consonants):
    vowelcount = 0
    consonantcount = 0
    for letter in string:
        if letter in "aeiou": #Detect if letter is in vowel list
            vowelcount += 1
        elif letter in "bcdfghjklmnpqrstvwxyz":
            consonantcount += 1
    if count_consonants:
        return consonantcount
    else:
        return vowelcount

Answered by ObsoleteAwareProduce on November 22, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP