Home > Blockchain >  Create all possible combination of words using letters also fix letters and shuffle it
Create all possible combination of words using letters also fix letters and shuffle it

Time:09-19

I am new to coding. please help me out with this, Task: Lets say I want to create all possible 6 letter words, Also I want a, b ,c present in all words. Position of a,b,c should also be changed in all possible ways in different combination. If 3 letters are fixed rest can be a to z, repetition allowed

CodePudding user response:

You can create all combinations of 6 letters with itertools.product. You can then filter all combinations that include a, b, c no matter the order.

Please note that you create 26**6=308.915.776 tuples that are not all real "words" - not sure if you really want to do that.

from itertools import product
from string import ascii_lowercase


relevant = (comb for comb in product(ascii_lowercase, repeat=6) if all(char in comb for char in ("a", "b", "c")))
next(relevant)  # ('a', 'a', 'a', 'a', 'c', 'b')
list("".join(char) for char in relevant)

CodePudding user response:

If you want to be a bit more efficient than generating all combinations of 6 letters, you can create all permutations of a,b and c, then insert all alphabet letters in between them:

import string
from itertools import permutations

letters = list(string.ascii_lowercase) #alphabet
words = [ ''.join(x) for x in permutations(["a", "b", "c"], 3)] # permutations of a,b and c
for maxpos in [4,5,6]: #insert all alphabet letters at all positions for all current words
    words = [w[:i]   l   w[i:] for l in letters for i in range(maxpos) for w in words]

Check result :

all(l in word for l in ("a", "b", "c") for word in words)

Output

True
  • Related