Search for all vowel replacement combinations

I try to find all possible combinations for all vowels in one word. So, for example, for "hello":

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

I wrote the following function that will simply accept every vowel, and in each vowel it will simply replace all the vowels and add each version to the list. I am trying to change this into a wildcard as I want, but it does not work. I tried to insert vowels ("". Join (string), arr) after adding, but this leads to 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?

+4
source share
1 answer

Once the corrected CristopheD clause is corrected, your function returns this:

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

... therefore it returns some of the possible combinations, but not all of them.

This is because he takes each vowel in the word in turn and replaces it with each vowel in turn, and then moves on to the next vowel in the word - but not taking into account the previous vowels (s) that he found when he falls into the next. Here's a recursive solution that 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)) 
+2
source

Source: https://habr.com/ru/post/1444695/


All Articles