tags:

views:

92

answers:

4
+1  Q: 

Counting vowels

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()
+1  A: 

Your test expects the function to print the vowels it found, but you're printing the count instead. You're also passing it the variable test instead of the string 'test', you need to do

>>> find_vowels('test')

Finally, the indenting is off, but I assume that was a pasting problem

Michael Mrozek
+2  A: 

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']
Mark Rushakoff
-1 building a LIST of vowels just to count them is not "pythonic" ... consider `sum(letter in vowels for letter in test)` AND vowels should be a set, not list.
John Machin
@John: Valid point on the counting, but I disagree in regards to using a set. From what we know about the specifications (nothing), should `find_vowels('wheel')` return `'e'` or `['e', 'e']`? I assumed it was the latter.
Mark Rushakoff
@Mark: I meant "vowels should be a set, not sequence" i.e. set("aeiouAEIOU") not "aeiouAEIOU" ... `vowels` is used to check the INPUT (`letter in vowels`) of both a count function and a "find" function; it's nothing to do with the OUTPUT from a "find" function.
John Machin
+3  A: 

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!

Alex Martelli
Great thank you very much! That did it
Then you could consider accepting it (by clicking on the checkmark icon below the big number on the question's upper left) and (once you've got the extra rep that comes from accepting, which puts you above the threshold for being able to upvote) upvoting (clicking the triangle above the already-mentioned big number). Basic SO etiquette: thanks are nice and all, but accepts and upvotes are what makes SO go around!-)
Alex Martelli
A: 

You need to indent the body of find_vowels.

Keith Randall