Count the number of vowelgroups in a string I've written a function that can count the vowel groups in a string.

def count_vowelgroups(woord):
    if woord[0].lower() in 'aeiouy':
        output = 1
    else:
        output = 0

    for i in range(1, len(woord)):
        if woord[i].lower() in 'aeiouy' and woord[i-1].lower() not in 'aeiouy':
            output += 1
    return output


It works fine, but not really pythonic! Who can help?

For example:

print(count_vowelgroups('Hello everyone!'))
6
print(count_vowelgroups('Alright'))
2
print(count_vowelgroups('Whaaaaaat!?'))
1
print(count_vowelgroups('Je pense donc je suis.'))
6
Using the itertools recipe pairwise you can directly use sum to calculate the number of vowel groups by iterating over pairs of values.

In addition I would make the vowels a global constant and a set, because building the string every time is going to cost some time. Also, sets have very fast membership testing.

With these changes you would get:

from itertools import tee, izip

VOWELS = set("aeiouy")

def pairwise(iterable):
    """s -&gt; (s0,s1), (s1,s2), (s2, s3), ..."""
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

def count_vowelgroups(words):
    words = words.lower()
    return sum(c_1 not in VOWELS and c in VOWELS for c_1, c in pairwise(words))