How To Generate Combination Of Fix Length Strings Using A Set Of Characters?
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 permutation
Solution 1:
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)]
Solution 2:
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)]
Post a Comment for "How To Generate Combination Of Fix Length Strings Using A Set Of Characters?"