T. Kearsley
T. Kearsley

Reputation: 307

All possible combinations of a set as a list of strings

I am trying to write a function in Python

def all_strings(alpha,length):
    # ...

which takes a given alphabet (alpha) and a length and returns all possible combinations of the alphabet restricted by the given length.

For example:

all_strings({0,1}, 3)

should return:

['000', '001', '010', '011', '100', '101', '110', '111']

I tried looping through the set but you cannot iterate through a set in python. I also considered itertools however permutations and combinations do not allow repetition of numbers.

Upvotes: 1

Views: 1193

Answers (1)

MSeifert
MSeifert

Reputation: 152810

You can use itertools.product:

>>> from itertools import product

>>> list(product({0,1}, repeat=3))
[(0, 0, 0),
 (0, 0, 1),
 (0, 1, 0),
 (0, 1, 1),
 (1, 0, 0),
 (1, 0, 1),
 (1, 1, 0),
 (1, 1, 1)]

You can also str.join the results to get the strings:

>>> list(''.join(map(str, comb)) for comb in product({0,1}, repeat=3))
['000', '001', '010', '011', '100', '101', '110', '111']

And if you care about efficiency one can also convert the initial set to a set of strings to minimize the string conversions (thanks @Stefan Pochmann for pointing this out in the comments):

>>> list(map(''.join, product(map(str, {0,1}), repeat=3)))
['000', '001', '010', '011', '100', '101', '110', '111']

Upvotes: 3

Related Questions