1

In Python, how can I generate a string with all combinations of a set of characters up to a certain length?

I know how to use itertools to generate all combinations and permutations, but I can't figure out how to generate strings of dynamic length.

For example:

a = [0,1] length = 4

Result:

[0000, 0001, 0010, 0011, 0100, 0101, 0110, 0111, 1000, 1001, 1101, 1110, 1111]

drum
  • 5,416
  • 7
  • 57
  • 91
  • 1
    You asked for strings "up to a certain length", but in your example, you only give the results with exactly that length. – Sven Marnach Sep 12 '13 at 19:27
  • That's a good point. I was going to loop a function with range() once I figured out how to generate results of fixed length. – drum Sep 12 '13 at 19:30

2 Answers2

5

You could use itertools.product:

li = []
for i in itertools.product([0,1], repeat=4):
    li.append(''.join(map(str, i)))
print (li)

>>> li
['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111']

Possible one liner:

[''.join(map(str, i)) for i in itertools.product([0,1], repeat=4)]
Ankur Ankan
  • 2,953
  • 2
  • 23
  • 38
3

use product from itertools module.

>>> from itertools import product
>>> [i for i in product([0,1],repeat=4)]
[(0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 1, 0), (0, 0, 1, 1), (0, 1, 0, 0), (0, 1, 0, 1), (0, 1, 1, 0), (0, 1, 1, 1), (1, 0, 0, 0), (1, 0, 0, 1), (1, 0, 1, 0), (1, 0, 1, 1), (1, 1, 0, 0), (1, 1, 0, 1), (1, 1, 1, 0), (1, 1, 1, 1)]
DhruvPathak
  • 42,059
  • 16
  • 116
  • 175