Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting vowels

Tags:

python

Can anyone please tell me what is wrong with this script. I am a python newb but i cant seem to figure out what might be causing it not to function.

def find_vowels(sentence):

    """
    >>> find_vowels(test)
    1

    """

    count = 0
    vowels = "aeiuoAEIOU"
    for letter in sentence:
        if letter in vowels:
            count += 1
    print count

if __name__ == '__main__':
    import doctest
    doctest.testmod()
like image 709
shaytac Avatar asked May 28 '10 02:05

shaytac


2 Answers

You're printing count (a number), but your test expects the letter e.

Also, the more Pythonic way to count the vowels would be a list comprehension:

>>> len([letter for letter in 'test' if letter in vowels])
1

Want to see the vowels you've found? Just drop that leading len function:

>>> [letter for letter in 'stackoverflow' if letter in vowels]
['a', 'o', 'e', 'o']
like image 100
Mark Rushakoff Avatar answered Sep 19 '22 10:09

Mark Rushakoff


Besides the fact that you're returning a count but expecting a string of vowels, as others have said, you must also change the line

>>> find_vowels(test)

to

>>> find_vowels('test')

You forgot the quotes!

like image 37
Alex Martelli Avatar answered Sep 21 '22 10:09

Alex Martelli