I have a list of two items: L = [(0), (1)] I would like to obtain a list of lists containing all possible combinations of length n.
For example, with n = 2
JavaScript
x
5
1
[[(0), (0)],
2
[(0), (1)],
3
[(1), (0)],
4
[(1), (1)]]
5
I have already tried with combinations of itertools but it doesn’t work if n is greater than the number of elements in L. I found combinations_with_replacement, but with n = 10 it only creates 11 possible combinations, and not 1024 as it should be.
JavaScript
1
6
1
from itertools import combinations_with_replacement
2
L = [(0), (1)]
3
n = 10
4
def combo(L,n):
5
return list(combinations_with_replacement(l, n))
6
Output:
JavaScript
1
2
1
[(0, 0, 0, 0, 0, 0, 0, 0, 0, 0), (0, 0, 0, 0, 0, 0, 0, 0, 0, 1), (0, 0, 0, 0, 0, 0, 0, 0, 1, 1), (0, 0, 0, 0, 0, 0, 0, 1, 1, 1), (0, 0, 0, 0, 0, 0, 1, 1, 1, 1), (0, 0, 0, 0, 0, 1, 1, 1, 1, 1), (0, 0, 0, 0, 1, 1, 1, 1, 1, 1), (0, 0, 0, 1, 1, 1, 1, 1, 1, 1), (0, 0, 1, 1, 1, 1, 1, 1, 1, 1), (0, 1, 1, 1, 1, 1, 1, 1, 1, 1), (1, 1, 1, 1, 1, 1, 1, 1, 1, 1)]
2
any suggestions?
Advertisement
Answer
itertools.product is what you want here:
JavaScript
1
5
1
import itertools
2
3
def combo(L,n):
4
return itertools.product(L, repeat=n)
5
For example:
JavaScript
1
14
14
1
>>> my_iter = product([0, 1], repeat=10)
2
>>> next(my_iter)
3
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
4
>>> next(my_iter)
5
(0, 0, 0, 0, 0, 0, 0, 0, 0, 1)
6
>>> next(my_iter)
7
(0, 0, 0, 0, 0, 0, 0, 0, 1, 0)
8
>>> next(my_iter)
9
(0, 0, 0, 0, 0, 0, 0, 0, 1, 1)
10
>>> next(my_iter)
11
(0, 0, 0, 0, 0, 0, 0, 1, 0, 0)
12
>>> next(my_iter)
13
(0, 0, 0, 0, 0, 0, 0, 1, 0, 1)
14