3

I'm trying to generate all possible bytes to test for a machine learning algorithm (8-3-8 mural network encoder). is there a way to do this in python without having 8 loops?

Could permutations help?

I'd prefer an elegant way to do this, but I'll take what I can get at the moment.

desired output:

[0,0,0,0,0,0,0,0]
[0,0,0,0,0,0,0,1]
[0,0,0,0,0,0,1,0]
[0,0,0,0,0,0,1,1]
[0,0,0,0,0,1,0,0]
[0,0,0,0,0,1,0,1]
.
.
.
[1,1,1,1,1,1,1,1]
1
  • also, order is not important! just so that I have one of each! Commented Mar 21, 2013 at 2:22

4 Answers 4

11

Yes, there is, itertools.product:

import itertools


itertools.product([0, 1], repeat=8)
>>> list(itertools.product([0, 1], repeat=8))
[(0, 0, 0, 0, 0, 0, 0, 0),
 (0, 0, 0, 0, 0, 0, 0, 1),

[...]

 (1, 1, 1, 1, 1, 1, 1, 0),
 (1, 1, 1, 1, 1, 1, 1, 1)]
Sign up to request clarification or add additional context in comments.

1 Comment

@DSM Thanks again, I wasn't paying attention.
6
[[x>>b&1 for b in range(8)] for x in range(256)]

Comments

4

You could iterate over the numbers and then convert to binary:

[bin(x)[2:] for x in range(256)]

Comments

1

If you happen to be using numpy already...

In [48]: import numpy as np

In [49]: nbits = 4

In [50]: np.sign(np.bitwise_and(2 ** np.arange(nbits), np.arange(2 ** nbits).reshape(-1, 1)))
Out[50]: 
array([[0, 0, 0, 0],
       [1, 0, 0, 0],
       [0, 1, 0, 0],
       [1, 1, 0, 0],
       [0, 0, 1, 0],
       [1, 0, 1, 0],
       [0, 1, 1, 0],
       [1, 1, 1, 0],
       [0, 0, 0, 1],
       [1, 0, 0, 1],
       [0, 1, 0, 1],
       [1, 1, 0, 1],
       [0, 0, 1, 1],
       [1, 0, 1, 1],
       [0, 1, 1, 1],
       [1, 1, 1, 1]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.