vowels = "aeiou"
consonants = "bcdfghjklmnpqrstvwxyz"
I'm trying to make a function that would only return constants followed by vowels in a list.
So for example:
f("therapist")
>>>["he", "ra", "pi"]
f("apple")
>>>["le"]
So it's only when a vowel follows a consonant and it returns both the consonant and the vowel in a list.
I was thinking it would be something along the lines of:
def f(word):
for consonant in word:
for vowel in word:
But I don't know how to work with the order and test whether the vowel is after the consonant. Thanks in advance
You can use enumerate with a starting index of 1, checking if the current ele is a consonant and the next chaarcter word[i]
is a vowel.
def f(word):
vowels = {"a", "e", "i", "o", "u"}
consonants = {'t', 'b', 'm', 'h', 'y', 'w', 'z', 'p', 'v', 'd', 'g', 'k', 'j', 'n', 'r', 'q', 'x', 'c', 's','f', 'l'}
return [ele + word[i] for i, ele in enumerate(word[:-1], 1)
if word[i] in vowels and ele in consonants ]
Or using loops keep track of the last character and compare:
def f(word):
vowels = {"a", "e", "i", "o", "u"}
consonants = {'t', 'b', 'm', 'h', 'y', 'w', 'z', 'p', 'v', 'd', 'g', 'k', 'j', 'n', 'r', 'q', 'x', 'c', 's','f', 'l'}
pairs = []
it = iter(word)
# get first char
prev = next(it,"")
# iterate over the rest starting at the second char
for ch in it:
# compare prev and current
if prev in consonants and ch in vowels:
pairs.append(prev + ch)
# update prev
prev = ch
return pairs
You can use regex :
>>> import re
>>> def f(s):
... return re.findall(r'[bcdfghjklmnpqrstvwxyz][aeiou]',s)
...
>>> f('therapist')
['he', 'ra', 'pi']
Also you can use zip
within a list comprehension :
>>> def f(s):
... return [''.join((i,j)) for i,j in zip(s,s[1:]) if i in 'bcdfghjklmnpqrstvwxyz' and j in 'aeiou']
...
>>> s='therapist'
>>> f(s)
['he', 'ra', 'pi']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With