Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a cleaner way to iterate through all binary 4-tuples?

Tags:

python

This does what I want it to do:

import itertools
list(itertools.product(*[[0,1]]*4))

Output:

[(0, 0, 0, 0),
 (0, 0, 0, 1),
 (0, 0, 1, 0),
 (0, 0, 1, 1),
 (0, 1, 0, 0),
 (0, 1, 0, 1),
 (0, 1, 1, 0),
 (0, 1, 1, 1),
 (1, 0, 0, 0),
 (1, 0, 0, 1),
 (1, 0, 1, 0),
 (1, 0, 1, 1),
 (1, 1, 0, 0),
 (1, 1, 0, 1),
 (1, 1, 1, 0),
 (1, 1, 1, 1)]

But it's a bit obfuscated to me. Is there a more pythonic way to do it?

like image 440
Hilemonstoer Avatar asked Dec 25 '22 15:12

Hilemonstoer


1 Answers

itertools.product takes a repeat argument which simplifies it a bit as it avoids the argument unpacking and therefor the list multiplication:

itertools.product(range(2), repeat=4)

This is even called out in the official documentation1 (though the example uses repeat=3).

1Note, I used range(2) rather than (0, 1) or [0, 1] since that's how it's written in the documentation. Either way will work :) (obviously)

like image 195
mgilson Avatar answered Feb 08 '23 23:02

mgilson