1

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

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

There isn't any explanation on here - I would add some for the benefit of our poster if you get time :)
1

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'

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.