Jo Costa
Jo Costa

Reputation: 441

Python Itertools Combinatinos retrieving empty list

I am trying to generate a list or dataframe with combinations of [0 , 1] for 14 different places. However

I am getting an empty list or a message of :

[itertools.combinations at 0x29b294cc0e8]

There are actually a few solutions for the problem which I tried, none appear to work.

d = [0, 1]

result = itertools.combinations(d, 14)
for each in result:
    print(each)

results = [x for x in itertools.combinations(d, 14)]

From my calculations I should get a list of 2^ 14 combinations (16384) of zeros and ones.

Upvotes: 1

Views: 1651

Answers (3)

maxwu
maxwu

Reputation: 432

Please try combinations_with_replacement since the 0, 1 are repeatable.

import itertools as it
results = list(it.combinations_with_replacement([0,1], 14))

results:

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

Upvotes: 0

Fissium
Fissium

Reputation: 321

itertools.combinations (iterable, [r]) - combinations of length r from iterable without duplicate elements. But you only have 2 elements, and you want a sequence of 14 elements long. Perhaps worth using itertools.combinations_with_replacement.

Upvotes: 0

LazyCoder
LazyCoder

Reputation: 1265

The code required is :

import itertools
d = [0, 1]
lst = list(itertools.product(d, repeat=14))

Upvotes: 1

Related Questions