1

So this is what im trying in Python.`

input = []
for i in range(10):
  n = getBin(i, 4)
  input.append(n)
print input

It is giving as:

['0000', '0001', '0010', '0011', '0100', 
 '0101', '0110', '0111', '1000', '1001']

And what I need is as:

[[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]]
0

2 Answers 2

1

Using itertools.product with (0, 1) and 4 repeats:

input = [list(x) for x in itertools.product((0, 1), repeat=4)]

If you're ok with a list of tuples rather than of lists, you can simply do:

input = list(itertools.product((0, 1), repeat=4))

Or simplest of all, if you will be iterating over it anyway, there's no need to make it a list:

input = itertools.product((0, 1), repeat=4)

Lastly, (0, 1) could be range(2), but that's hardly an improvement


itertools.product generally tries to return in the same format you gave it. So by feeding a string, it returns a string. Feed it a list and it...almost returns a list (returns a tuple)

Sign up to request clarification or add additional context in comments.

5 Comments

Not sure but I think OP don't want this technique.
The first option is what i want.In the same way i want for floating points and the number will contain around 10 digits after point (ex. 0.0001221215). The number will vary from 0 to 2500.
@GrijeshChauhan, I assumed this new question was an implementation detail of the previous, as previous output was the input to this question. Using that knowledge, I'm changing the itertools.product in getBin to provide the solution without any additional layer of code
@GrijeshChauhan ok.. i m adding new question for the above
how can i save these binary numbers in txt file.Each line should contain 4 bits as from above question.
1

Your getBin returns a binary number in string format, we convert each and every character to an integer with int and return a list.

result = [map(int, getBin(i,4)) for i in range(10)]

For example,

def getBin(number, total):
    return bin(number)[2:].zfill(total)

result = [map(int, getBin(i, 4)) for i in range(10)]

print result

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

2 Comments

is getBin any library function?
@GrijeshChauhan Nope. OP hasn't shown how that is implemented. So, I had to implement it on my own. Its there in my answer itself. Please check.

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.