Creating a matrix of options using itertools
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Drifting Through My Dreams
--
Chapters
00:00 Question
00:48 Accepted answer (Score 8)
01:09 Answer 2 (Score 4)
01:38 Answer 3 (Score 2)
02:17 Thank you
--
Full question
https://stackoverflow.com/questions/7046...
Accepted answer links:
[itertools.product]: http://docs.python.org/library/itertools...
Answer 2 links:
[Frederick]: https://stackoverflow.com/questions/7046...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #itertools
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Drifting Through My Dreams
--
Chapters
00:00 Question
00:48 Accepted answer (Score 8)
01:09 Answer 2 (Score 4)
01:38 Answer 3 (Score 2)
02:17 Thank you
--
Full question
https://stackoverflow.com/questions/7046...
Accepted answer links:
[itertools.product]: http://docs.python.org/library/itertools...
Answer 2 links:
[Frederick]: 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.