[SOLVED] Convert list of integers into list of binary digits

Issue

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?

Solution

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

Answered By – user15471954

Answer Checked By – Mildred Charles (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *