Reputation: 63
I've written a script that gets n bit values and put them together in a list. I need to make the result in binary. It gives me errors in every single method/function I try. I'm fairly new to Python, I would appreciate some help.
from itertools import product
arr = 0
val_x = []
val_y =[]
n = int(input('n = '))
if __name__ == "__main__":
for x in range (0, n + 1):
for y in range (0, n + 1):
if y == 0:
arr += 1
if arr == 1:
val_x.append(x)
val_y.append(x)
arr = 0
res = list(product(val_x, val_y))
print(res)
The result I get is:
n = 2
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
I need it in binary like this:
[(00, 00), (00, 01), (00, 10), (01, 00), (01, 01), (01, 10), (10, 00), (10, 01), (10, 10)]
Upvotes: 1
Views: 99
Reputation: 14949
Using bin ->
from itertools import product
arr = 0
val_x = []
val_y =[]
n = int(input('n = '))
if __name__ == "__main__":
for x in range(n + 1):
for y in range(n + 1):
if y == 0:
arr += 1
if arr == 1:
val_x.append(bin(x)[2:]) #by bin you can convert the int to binary
val_y.append(bin(x)[2:])
arr = 0
res = list(product(val_x, val_y))
print(res)
Using f-strings(as suggested by ash)- Here, the idea is instead of appending integers append their binary format.
from itertools import product
arr = 0
val_x = []
val_y =[]
n = int(input('n = '))
if __name__ == "__main__":
for x in range(n + 1):
for y in range(n + 1):
if y == 0:
arr += 1
if arr == 1:
val_x.append(f"{x:02b}")
val_y.append(f"{x:02b}")
arr = 0
res = list(product(val_x, val_y))
print(res)
Upvotes: 2
Reputation: 364
the good news is that your binary is being stored correctly, you can do whatever you like to it - when you want to represent it as binary you can use string formatting with b
get a binary string out.
>>> a = 5
>>> f"{a:b}"
'101'
If you want it to be a certain length (always 2 in your case) you can do this:
>>> a = 0
>>> f"{a:02b}"
'00'
Upvotes: 1