Manas Chaturvedi
Manas Chaturvedi

Reputation: 5540

Generating all permutations of a list of strings

I have a list of strings: ['red','blue','pink'] and I'm trying to generate a list of all permutations of the elements of the given list as follows:

['red', 'redblue', 'redbluepink', 'redpinkblue',
 'blue', 'bluered', 'bluepink', 'blueredpink', 'bluepinkred',
 'pink', 'pinkred', 'pinkblue', 'pinkredblue', 'pinkbluered']

I have managed to write the following code to generate all the forward permutations of the elements of a list:

from itertools import combinations

def all_permutations(list_of_strings):
    results = [''.join(list_of_strings[i:j]) for i, j in combinations(range(len(list_of_strings) + 1), 2)]

    return results

print(all_permutations(['red','blue','pink']))

However, this code only manages to generate all the forward permutations:

['red', 'redblue', 'redbluepink', 'blue', 'bluepink', 'pink']

Could anyone help me figure out a way to generate all the permutations of the elements from a list of strings?

Upvotes: 4

Views: 183

Answers (2)

Mad Physicist
Mad Physicist

Reputation: 114320

You can use the second parameter to itertools.permutations, r to get the iterator you want:

from itertools import permutations

def all_permutations(x):
    for r in range(1, len(x) + 1):
        yield from permutations(x, r)

To combine the result:

[''.join(s) for s in all_permutations(['red', 'blue', 'pink'])]

Or

map(''.join, all_permutations(['red', 'blue', 'pink']))

This will give you an order different from the one in the question. You can impose the order you want by sorting according to the index in your original list:

items = ['red', 'blue', 'pink']
index = {k: i for i, k in enumerate(items)}
all_items = sorted(all_permutations(items), key=lambda item: tuple(index[x] for x in item))
all_items = [''.join(item) for item in all_items]

Upvotes: 3

cody
cody

Reputation: 11157

The following solution may meet your needs. Your solution is using itertools.combinations, and the key difference between permutations and combinations is that order does not matter in combinations, such that 'redblue' and 'bluered' would not be unique.

from itertools import permutations

def all_permutations(l):
    o = []
    for x in range(1, len(l) + 1):
        o.extend([''.join(p) for p in list(permutations(l, x))])
    return o

colors = ['red', 'blue', 'pink']

print(all_permutations(colors))

Result:

['red', 'blue', 'pink', 'redblue', 'redpink', 'bluered', 'bluepink', 'pinkred', 'pinkblue', 'redbluepink', 'redpinkblue', 'blueredpink', 'bluepinkred', 'pinkredblue', 'pinkbluered']

Upvotes: 2

Related Questions