Home > OS >  Obtain a list of all combinations of two elements with length n
Obtain a list of all combinations of two elements with length n

Time:11-17

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

[[(0), (0)],
[(0), (1)],
[(1), (0)],
[(1), (1)]]

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.

from itertools import combinations_with_replacement
L = [(0), (1)]
n = 10
def combo(L,n):
    return list(combinations_with_replacement(l, n))

Output:

[(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)]

any suggestions?

CodePudding user response:

itertools.product is what you want here:

import itertools

def combo(L,n):
    return itertools.product(L, repeat=n)

For example:

>>> my_iter = product([0, 1], repeat=10)
>>> next(my_iter)
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
>>> next(my_iter)
(0, 0, 0, 0, 0, 0, 0, 0, 0, 1)
>>> next(my_iter)
(0, 0, 0, 0, 0, 0, 0, 0, 1, 0)
>>> next(my_iter)
(0, 0, 0, 0, 0, 0, 0, 0, 1, 1)
>>> next(my_iter)
(0, 0, 0, 0, 0, 0, 0, 1, 0, 0)
>>> next(my_iter)
(0, 0, 0, 0, 0, 0, 0, 1, 0, 1)
  • Related