Home > Blockchain >  Convert list of integers into list of binary digits
Convert list of integers into list of binary digits

Time:02-24

Create a function that takes as input a list of integers, and which outputs a list of the binary digit lists obtained from your integertobinary() function. The order in which the binary digit lists appear should match the order of the list of input integers.

For example, if the input to your function is [14,3,8,5] the output should be [[1,1,1,0],[1,1],[1,0,0,0],[1,0,1]].

Here is what I have done so far:

def integertobinary(L): 
    for n in L:
        y = []
        while(n>0):
            a=n%2
            y.append(a)
            n=n//2
        y.reverse()
    return y

    print(integertobinary([5,6,7,8,9]))

As a result, I am getting: [1, 0, 0, 1] when I am supposed to get [[1,1,1,0],[1,1],[1,0,0,0],[1,0,1]]. What am I doing wrong?

CodePudding user response:

The reason seems to be that you clear the value of y in every iteration. You need to make another variable to store all the values. The code might be:

def integertobinary(L): 
    y = []
    for n in L:
        z = []
        while(n>0):
            a=n%2
            z.append(a)
            n=n//2
        z.reverse()
        y.append(z)
    return y
print(integertobinary([5,6,7,8,9]))

Output:

[[1, 0, 1], [1, 1, 0], [1, 1, 1], [1, 0, 0, 0], [1, 0, 0, 1]]

CodePudding user response:

Another way to do this on a 1-D list could be:

a=  [14,3,8,5]
bin_list = [list(map(int, list(f"{x:b}"))) for x in a]

Output:

[[1, 1, 1, 0], [1, 1], [1, 0, 0, 0], [1, 0, 1]]

CodePudding user response:

You can do this in a simpler pythonic way, if you don't have a requirement of writing binary conversion logic. Just use the format or bin function in python for this. An eg.

def integertobinary(L):
    return [[int(b) for b in format(i, "04b")] for i in L]

would do the exact need. "04b" gives a binary formatted value with padding upto 4 leading zeroes.

print(integertobinary([14, 3, 8, 5]))

gives output

[[1, 1, 1, 0], [0, 0, 1, 1], [1, 0, 0, 0], [0, 1, 0, 1]]
  • Related