Generate All Possibles Combinations of an Array with a Length Within a Given Range

Python: Generating all n-length arrays combinations of values within a range

You can use itertools.product which is just a convenience function for nested iterations. It also has a repeat-argument if you want to repeat the same iterable multiple times:

>>> from itertools import product

>>> amin = 0
>>> amax = 2
>>> list(product(range(amin, amax), repeat=3))
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]

To get the list of list you could use map:

>>> list(map(list, product(range(amin, amax), repeat=3)))
[[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]]

However product is an iterator so it's really efficient if you just iterate over it instead of casting it to a list. At least if that's possible in your program. For example:

>>> for prod in product(range(amin, amax), repeat=3):
... print(prod) # one example
(0, 0, 0)
(0, 0, 1)
(0, 1, 0)
(0, 1, 1)
(1, 0, 0)
(1, 0, 1)
(1, 1, 0)
(1, 1, 1)

Getting all possible combination for [1,0] with length 3 [0,0,0] to [1,1,1]

You're looking for a Cartesian product, not a combination or permutation of [0, 1]. For that, you can use itertools.product.

from itertools import product

items = [0, 1]

for item in product(items, repeat=3):
print(item)

This produces the output you're looking for (albeit in a slightly different order):

(0, 0, 0)
(0, 0, 1)
(0, 1, 0)
(0, 1, 1)
(1, 0, 0)
(1, 0, 1)
(1, 1, 0)
(1, 1, 1)

How to create a 2D array with all possible combinations of a constrained range for each column

You can do it easily with the built-in itertools.product:

import itertools as it

perms = np.array(list(it.product(a, b, c)))

Output:

>>> perms
array([[1001, 1, 1],
[1001, 1, 2],
[1001, 1, 3],
[1001, 1, 4],
[1001, 1, 5],
[1001, 2, 1],
[1001, 2, 2],
[1001, 2, 3],
[1001, 2, 4],
[1001, 2, 5],
[1001, 3, 1],
[1001, 3, 2],
[1001, 3, 3],
[1001, 3, 4],
[1001, 3, 5],
[1002, 1, 1],
[1002, 1, 2],
[1002, 1, 3],
[1002, 1, 4],
[1002, 1, 5],
[1002, 2, 1],
[1002, 2, 2],
[1002, 2, 3],
[1002, 2, 4],
[1002, 2, 5],
[1002, 3, 1],
[1002, 3, 2],
[1002, 3, 3],
[1002, 3, 4],
[1002, 3, 5]])

How to get all possible combinations of a list’s elements?

Have a look at itertools.combinations:

itertools.combinations(iterable, r)

Return r length subsequences of elements from
the input iterable.

Combinations are emitted in lexicographic sort order. So, if the
input iterable is sorted, the
combination tuples will be produced in
sorted order.

Since 2.6, batteries are included!



Related Topics



Leave a reply



Submit