开发者

Creating a matrix of options using itertools

I am trying to produce a matrix开发者_JAVA百科 of True and False values, which shows all the permutations for a given number of choices. So for 5 choices you would have the following output.

F F F F F
T F F F F
T T F F F
T T T F F
...
F T F F F
...

I have been looking at using itertool's permutations and combinations, but these work off position and not value which results in duplicates.

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


Use itertools.product:

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

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

(False, False)
(False, True)
(True, False)
(True, True)


You seem to want the n-dimensional cartesian product of [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 concisely (stealing 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)]


This is the same form as the binary representation of integers between 0 to (2**n)-1. If you were inclined to such perversity, you could represent integers as zero-padded binary strings using str.format() and then coerce the string (of the form "00101") into a boolean list by doing something terrible like this:

>>> 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 is, I'm sure, the right way to think about this, but this way made me giggle.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜