Home > OS >  How to get every string permutation where each letter is from a different string
How to get every string permutation where each letter is from a different string

Time:09-08

I have this block of code in python3:

keyLetters = []
for coset in cosets:
    keyLetters.append(Counter(coset).most_common(8))

Where cosets is a list of gibberish strings, and keyLetters are a list of the most common letters from each string.

My goal is to get every letter combination as a series of strings from their most common letters, where each position of the string is from a different coset.

So if the top three most frequent letters from three cosets are:

c1 = {'D', 'K', 'M'}
c2 = {'L', 'D', 'J'}
c3 = {'Z', 'B', 'F'}

I need the strings:

s1 = 'DDF'
s2 = 'DJF'
s3 = 'ZDM'
etc

How do I achieve this?

CodePudding user response:

You want the product of all your sets. With your example:

import itertools

c1 = {'D', 'K', 'M'}
c2 = {'L', 'D', 'J'}
c3 = {'Z', 'B', 'F'}

for chars in itertools.product(c1, c2, c3):
    print("".join(chars))

Which gives:

DDF
DDZ
DDB
DLF
DLZ
DLB
DJF
DJZ
DJB
KDF
KDZ
KDB
KLF
KLZ
KLB
KJF
KJZ
KJB
MDF
MDZ
MDB
MLF
MLZ
MLB
MJF
MJZ
MJB
  • Related