darksky
darksky

Reputation: 21049

Finding all combinations of vowel replacements

I am trying to find all possible combinations for all vowels in a word. So for example given 'hello':

[halla, halle, halli, hallo, hallu, hella, halle, halli, hallo, hallu...]

I have written the following function which will just take each vowel, and at each vowel, it will just replace it all with the vowels and add each version into a list. I'm trying to change that into the permutation as I want but it's not working. I tried inserting vowels("".join(string), arr) after the append but that results in infinite recursion.

def vowels(word, arr=None):
    if arr is None:
        a = []

    for i, c in enumerate(word):
        if c in 'aeiou':
            for v in 'aeiou':
                string = list(word)
                string[i] = v
                arr.append("".join(string))
    return arr

Does anyone have any suggestions?

Upvotes: 4

Views: 994

Answers (1)

schesis
schesis

Reputation: 59168

Once the typo CristopheD mentioned is fixed, your function returns this:

['hallo', 'hello', 'hillo', 'hollo', 'hullo', 'hella', 'helle', 'helli', 'hello', 'hellu']

... so it's returning some of the possible combinations, but not all of them.

That's because it's taking each vowel in the word in turn, and replacing it with each vowel in turn, then moving on to the next vowel in the word - but not taking into account the previous vowel(s) it found when it hits subsequent ones. Here's a recursive solution which works for words with any number of vowels:

import re

VOWELS = "aeiou"
RE_VOWEL = re.compile("[%s]" % VOWELS)

def helper(parts):
    if len(parts) == 1:
        yield parts[0]
    else:
        for vowel in VOWELS:
            for item in helper([vowel.join(parts[:2])] + parts[2:]):
                yield item

def vowels(word):
    parts = re.split(RE_VOWEL, word)
    return list(helper(parts))

Upvotes: 2

Related Questions