banana_99
banana_99

Reputation: 641

Permutations of two lists but it has to be alternating consonant and vowel

I have the string 'BANANA' (could be any).

I would like to find all possible permutations between characters but it needs to be one consonant and one vowel alternating.

So far, what I've achieved are normal permutations, but I'm struggling with the alternation part.

from itertools import permutations
# Set for avoiding duplicates
return set([''.join(j) for i in range(1, len(string_) + 1) for j
            in permutations(string_, i)])

The output I would expect is:

['B', 'A', 'N', 'BA', 'AN', 'NA', 'BAN', 'BANA', etc]

But not (since they would be consonant after consonant or vowel after vowel) things like:

['BN', 'NB', AA', etc]

Upvotes: 0

Views: 138

Answers (1)

Niel Godfrey P. Ponciano
Niel Godfrey P. Ponciano

Reputation: 10709

In your list comprehension, you can filter out permutations where there are consecutive vowels or consonants.

from itertools import permutations

VOWELS = {"A", "E", "I", "O", "U"}

string_ = "BANANA"

def is_alternating(text):
    def is_vowel(ch):
        return ch in VOWELS

    return all(
        is_vowel(text[index-1]) != is_vowel(text[index])
        for index in range(1, len(text))
    )

perms = set(
    [
        ''.join(j)
        for i in range(1, len(string_) + 1)
        for j in permutations(string_, i)
        if is_alternating(j)
    ]
)

print(perms)

Output

{'ANABA', 'BAN', 'ANANA', 'BANA', 'BANANA', 'AB', 'ANANAB', 'N', 'ABANAN', 'NABA', 'A', 'ANA', 'ABANA', 'ANAN', 'B', 'ANABAN', 'NAB', 'NAN', 'NABANA', 'AN', 'ABA', 'NABAN', 'BA', 'NANAB', 'ABAN', 'NANA', 'ANAB', 'NANABA', 'NA', 'BANAN'}

Upvotes: 2

Related Questions