The Python Oracle

Creating a matrix of options using itertools

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Quirky Dreamscape Looping

--

Chapters
00:00 Creating A Matrix Of Options Using Itertools
00:32 Accepted Answer Score 8
00:52 Answer 2 Score 4
01:10 Answer 3 Score 2
01:43 Thank you

--

Full question
https://stackoverflow.com/questions/7046...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #itertools

#avk47



ACCEPTED ANSWER

Score 8


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)



ANSWER 2

Score 4


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)]



ANSWER 3

Score 2


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.