Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting the letters of a word based on conditions, and returning in a list (Python)

Tags:

python

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

like image 672
Roger Avatar asked Jan 08 '23 14:01

Roger


2 Answers

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
like image 104
Padraic Cunningham Avatar answered Jan 19 '23 00:01

Padraic Cunningham


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']
like image 38
Mazdak Avatar answered Jan 18 '23 22:01

Mazdak