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.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With