Reputation: 612
I would like to know a simple and pythonic way to get all strings of length n that are composed of the characters contained in a list called L.
For example:
L = ['0','1']
n = 3
How do I get:
['000','001','010','011','100','101','110','111']
A possible solution is by using itertools.product
. It works, but it's not very elegant, so I'm looking for a more pythonic solution.
Here's how it would be:
L = ['0','1']
n = 3
a = [L for i in range(n)]
x = list(itertools.product(*a))
x = ["".join(i) for i in x]
The resulting list looks like this:
>>> x
['000', '001', '010', '011', '100', '101', '110', '111']
Is there something built-in like all_possible_strings(L, n)
, which takes the elements in L and obtains all possible combinations of length n with those elements?
Upvotes: 0
Views: 673
Reputation: 5455
Using the repeat option of product seems to give you what you want more directly:
L = ['0','1']
n = 3
x = list(itertools.product(L, repeat=n))
x = ["".join(i) for i in x]
print(x)
Output:
['000', '001', '010', '011', '100', '101', '110', '111']
Upvotes: 2
Reputation: 9
The following code with Python 2.6 and above ONLY
First, import itertools:
import itertools
Permutation (order matters):
print list(itertools.permutations([1,2,3,4], 2))
[(1, 2), (1, 3), (1, 4),
(2, 1), (2, 3), (2, 4),
(3, 1), (3, 2), (3, 4),
(4, 1), (4, 2), (4, 3)]
Documentation:
https://docs.python.org/2/library/itertools.html#itertools.permutations
Happy Coding
Upvotes: 1