1

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.

MSeifert
  • 145,886
  • 38
  • 333
  • 352
T. Kearsley
  • 197
  • 3
  • 18

1 Answers1

3

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']
MSeifert
  • 145,886
  • 38
  • 333
  • 352
  • I have done the following `from itertools import product def all_strings(alpha,length): return_list = list(product(alpha,repeat=length)) return return_list` Can I get it to return the list as `['000', '001', '010'....` Rather than `[(0,0,0),(0,0,1)....` – T. Kearsley Mar 04 '17 at 02:25
  • The second part of the answer, the one about the `str.join`, shows just that: `list(''.join(map(str, comb)) for comb in product(alpha, repeat=length))` – MSeifert Mar 04 '17 at 02:26
  • 2
    `list(map(''.join, product(map(str, {0,1}), repeat=3)))` should be faster because it converts to strings only once and maybe also because of `map` instead of the generator expression. – Stefan Pochmann Mar 04 '17 at 02:47
  • @StefanPochmann You're right that's definetly much faster! I edited the answer. – MSeifert Mar 04 '17 at 02:58