isopropylcyanide
isopropylcyanide

Reputation: 425

How do I fill a list in python with elements from a specific set?

If I have a set of integers which denote the values that a list element can take and a python list of a given length.

I want to fill the list with all possible combinations.

example

list length=3 and the my_set ={1,-1}

Possible combinations

[1,1,1],[1,1,-1],[1,-1,1],[1,-1,-1],
[-1,1,1],[-1,1,-1],[-1,-1,1],[-1,-1,-1]

I tried approaching with random.sample method from random class but it doesn't help. I did:

my_set=[1,-1]
from random import sample as sm
print sm(my_set,1)    #Outputs: -1,-1,1,1 and so on..(random)
print sm(my_set,length_I_require)        #Outputs**:Error

Upvotes: 1

Views: 1938

Answers (3)

Hooting
Hooting

Reputation: 1711

lst_length = 3
my_set = {1,-1}
result = [[x] for x in my_set]
for i in range(1,lst_length):
    temp = []
    for candidate in my_set:
        for item in result:
            new_item = [candidate]
            new_item += item
            temp.append(new_item)
    result = temp
print result

If the list length is 1, the result is a list whose elements equal to the set. Every time the list length increases one, the result can be gotten by append each element of the set to the resulted list.

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1124110

Use the itertools.product() function:

from itertools import product

result = [list(combo) for combo in product(my_set, repeat=length)]

The list() call is optional; if tuples instead of lists are fine to, then result = list(product(my_set, repeat=length)) suffices.

Demo:

>>> from itertools import product
>>> length = 3 
>>> my_set = {1, -1}
>>> list(product(my_set, repeat=length))
[(1, 1, 1), (1, 1, -1), (1, -1, 1), (1, -1, -1), (-1, 1, 1), (-1, 1, -1), (-1, -1, 1), (-1, -1, -1)]
>>> [list(combo) for combo in product(my_set, repeat=length)]
[[1, 1, 1], [1, 1, -1], [1, -1, 1], [1, -1, -1], [-1, 1, 1], [-1, 1, -1], [-1, -1, 1], [-1, -1, -1]]

random.sample() gives you a random subset of the given input sequence; it doesn't produce all possible combinations of values.

Upvotes: 1

Kasravnd
Kasravnd

Reputation: 107347

That's what itertools.product is for :

>>> from itertools import product
>>> list(product({1,-1},repeat=3))
[(1, 1, 1), (1, 1, -1), (1, -1, 1), (1, -1, -1), (-1, 1, 1), (-1, 1, -1), (-1, -1, 1), (-1, -1, -1)]
>>> 

And if you want the result as list you can use map to convert the iterator of tuples to list if list (in python3 it returns an iterator which as a more efficient way you can use a list comprehension ):

>>> map(list,product({1,-1},repeat=3))
[[1, 1, 1], [1, 1, -1], [1, -1, 1], [1, -1, -1], [-1, 1, 1], [-1, 1, -1], [-1, -1, 1], [-1, -1, -1]]

In python3 :

>>> [list(pro) for pro in product({1,-1},repeat=3)]
[[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: 3

Related Questions