0

I was trying to generate all possible combinations from the letters of strings in a list.

For example:

Input: ['jkl', 'ghi', 'def']
Output: ["jgd", "jge", "jgf", "jhd", "jhe", "jhf", "jid", "jie", "jif"...]
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
arkh
  • 53
  • 6

2 Answers2

4
lst = ['jkl', 'ghi', 'def']

import itertools
list(map("".join, itertools.product(*lst)))

# result:
['jgd',
 'jge',
 'jgf',
 'jhd',
 'jhe',
 'jhf',
 'jid',
 'jie',
 'jif',
 'kgd',
 'kge',
 'kgf',
 'khd',
 'khe',
 'khf',
 'kid',
 'kie',
 'kif',
 'lgd',
 'lge',
 'lgf',
 'lhd',
 'lhe',
 'lhf',
 'lid',
 'lie',
 'lif']
mcsoini
  • 6,280
  • 2
  • 15
  • 38
3

I can propose you a trivial algorithm to do the same, it is using recursion:

def associations(entry):
    while len(entry) > 2:
        to_treat_later = entry.pop()
        print(f"We will treat {to_treat_later} later")
        entry = associations(entry)
        entry.append(to_treat_later)
    else:
        print(f"we can start with {entry}")
        associated_entry = []
        for elt_1 in entry[0]:
            for elt_2 in entry[1]:
                associated_entry.append(f"{elt_1}{elt_2}")
        return [associated_entry]


def convert_entry(entry):
    converted_entry = []
    for elt in entry:
        list_elt = []
        for letter in elt:
            list_elt.append(letter)
        converted_entry.append(list_elt)
    return converted_entry


the_entry = ["jkl", "ghi", "def", "cfe"]
associations(convert_entry(the_entry))
Floh
  • 745
  • 3
  • 16