1

I'd like to generate all possible string variants based on a list of lists of characters.

i.e. the input:

[['A'], ['A', 'B'], ['B', 'D'], ['A', 'C'], ['B'], ['C']]

should yield:

['AABABC', 'ABDCBC', 'AABABC', 'ABDCBC', 'AABABC', 'ABDCBC', 'AABABC', 'ABDCBC']

The input is always 6 chars, for every char it can be either one or two variants.

I came up with the following solution:

import itertools


def levels(lst):
    nr_levels = 0
    for element in lst:
        if len(element) == 2:
            nr_levels += 1
    return nr_levels


def expand(data):
    results = []

    # calculate the number of results based on the "nesting" in the input data
    nr_results = 2**levels(data)
    # add an empty list for each result, so we can append the characters later
    for _ in range(nr_results):
        results.append([])

    # iterate through variants and add each variant to the prepared result
    # lists
    for variants in data:
        cycle = itertools.cycle(variants)
        for result in results:
            result.append(next(cycle))

    return results


if __name__ == '__main__':
    data = [['A'], ['A', 'B'], ['B', 'D'], ['A', 'C'], ['B'], ['C']]
    print(["".join(x) for x in expand(data)])

While this seems to work, it does not feel very pythonic and I was wondering if there is a better approach.

André Keller
  • 3,179
  • 3
  • 15
  • 23

0 Answers0