Home > Blockchain >  How to pair up the vowels and consonants of a string into all possible way in a list?
How to pair up the vowels and consonants of a string into all possible way in a list?

Time:06-05

For example: string = "edaca"

output = ['ac', 'ad', 'ec', 'ed']

I've only managed to seperate the string in 2 lists of consist of vowels and consonants without duplicates.

v_list = ['e', 'a']
c_list = ['d', 'c']

But I'm not sure how to pair them up to ['ac', 'ad', 'ec', 'ed'].

def get_vowel_consonant_pairs(letters):
    v_list = [] 
    c_list = [] 
    result_list = []
    vowels = "aeiou"
    consonant = "bcdfghjklmnpqrstvwxyz"
    for letter in letters:
        if letter not in v_list:
            if letter not in c_list:
                if letter in vowels:
                    v_list.append(letter)

                if letter in consonant:
                    c_list.append(letter)

CodePudding user response:

Here's a solution using sets to find the intersection of letters and vowels and consonants, and then itertools.product to find all the combinations:

import itertools

def get_vowel_consonant_pairs(letters):
    vowels = set('aeiou')
    consonants = set('bcdfghjklmnpqrstvwxyz')
    letters = set(letters)
    v_list = vowels & letters
    c_list = consonants & letters
    return [''.join(p) for p in itertools.product(v_list, c_list)]

get_vowel_consonant_pairs('edaca')

Output

['ac', 'ad', 'ec', 'ed']

If you don't want to use a library, you can use a list comprehension to put together the values:

return [''.join([v, c]) for c in c_list for v in v_list]

Note (as pointed out by @MadPhysicist) if letters can only contain letters, you don't need consonants, you can simply set

c_list = letters - vowels

CodePudding user response:

You can use

loop like this.

for v in v_list:
  for c in c_list:
    result_list.append(f"{v}{c}")
  • Related