Creating a parameter matrix using itertools

I am trying to create a matrix of True and False values โ€‹โ€‹that displays all permutations for a certain number of options. Thus, for 5 options you will get the following result.

FFFFF TFFFF TTFFF TTTFF ... FTFFF ... 

I was looking for the use of itertool permutations and combinations, but they do not work by position, not by value, which leads to duplication.

I'm sure there is a standard algorithm for this problem, but I'm struggling to find his name.

+7
source share
3 answers

Use itertools.product :

 itertools.product([False,True],repeat=5) 

example itertools.product([False,True],repeat=2) :

 (False, False) (False, True) (True, False) (True, True) 
+8
source

It seems you need an n-dimensional Cartesian product [False, True] .

 >>> print list(itertools.product(*(itertools.repeat((False, True), 3)))) [(False, False, False), (False, False, True), (False, True, False), (False, True, True), (True, False, False), (True, False, True), (True, True, False), (True, True, True)] 

Or more briefly (the theft from Frederick )

 >>> print list(itertools.product((False, True), repeat=3)) [(False, False, False), (False, False, True), (False, True, False), (False, True, True), (True, False, False), (True, False, True), (True, True, False), (True, True, True)] 
+4
source

This is the same form as the binary representation of integers from 0 to (2 ** n) -1. If you were prone to such perversity, you could represent integers as zero binary strings using str.format (), and then force the string (of the form โ€œ00101โ€) to the logical list, doing something terrible:

 >>> n = 5 >>> for i in xrange(2**n): ... [bool(int(j)) for j in ("{0:0>%db}" % n).format(i)] 

The n-dimensional Cartesian product above, I'm sure the right way to think about it, but this way made me giggle.

+2
source

All Articles