Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given a set of letters, how to create all possible combinations of a word with these letters, duplicated with a specified number?

Let's say I have the word "apple", the set of letters ['a', 'l', 'e'] and the number of repetition 3. From this I'd like to create the following set: ['aaapple', 'aaappllle', 'aaappllleee', 'appllle', 'appllleee', 'appleee'].

Here is what I've already tried:

l = ['a', 'l', 'e']
word = "apple"

for i in range(0, len(l)):
    print wordWithDuplicatedLetters = "".join(3*c if c == l[i] else c for c in word)

But this doesn't match all the combinations, and itertools doesn't seem to offer the possibility I'm looking for.

like image 693
ooj-001 Avatar asked Jan 27 '23 11:01

ooj-001


1 Answers

I don't think your example output has all possible combinations, mine below I think has them all. The trick here is to go through all combinations of any size which the function all_combinations below does.

import itertools

repeat = ['a', 'l', 'e']
word = 'apple'

def all_combinations(itr):
    lst = list(itr)
    for r in range(1, len(lst) + 1):  # set start to 0 if want to include []
        for perm in itertools.combinations(lst, r=r):
            yield perm   # or use yield from in py3

def all_repeats():
    for rep in all_combinations(repeat):
        yield ''.join(char * 3 if char in rep else char for char in word)

print(list(all_repeats()))

output

['aaapple',
 'appllle',
 'appleee',
 'aaappllle',
 'aaappleee',
 'appllleee',
 'aaappllleee']
like image 160
FHTMitchell Avatar answered May 18 '23 03:05

FHTMitchell