[Solved] Expanding the inline python code [closed]


First the final answer, which is really a one-liner. Some explanations follow

a = [88, 24, 128, 3]
[i + 1 for i, x in enumerate("".join(bin(n + 256)[3:] for n in a)) if x == "1"]

This yields

[2, 4, 5, 12, 13, 17, 31, 32]

First transformation:

def dec2bin(a):
    return [int(x) for x in "".join(bin(n + 256)[3:] for n in a)]

On your example

>>> dec2bin([88, 24, 128, 3])
[0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1]

Then to get positions

def positions(a):
    return [i for i in range(len(a)) if a[i] == 1]

The final output

>>> positions(dec2bin([88, 24, 128, 3]))
[1, 3, 4, 11, 12, 16, 30, 31]

Notice the values are off by 1, since Python arrays start at 0. To get your values, simply add 1 to the output values:

def positions(a):
    return [i + 1 for i in range(len(a)) if a[i] == 1]

If you really need them in hex (they will be strings, not numbers, since numbers have no intrinsic base):

>>> list(map(hex, _))
['0x1', '0x3', '0x4', '0xb', '0xc', '0x10', '0x1e', '0x1f']

The whole thing in one line

>>> v = [88, 24, 128, 3]
>>> (lambda a: [i + 1 for i in range(len(a)) if a[i] == 1])([int(x) for x in "".join(bin(n + 256)[3:] for n in v)])
[2, 4, 5, 12, 13, 17, 31, 32]

The lambda is not necessary, you can write this instead, using enumerate. And you can make the line shorter by removing the “int(x)” step:

>>> v = [88, 24, 128, 3]
>>> [i + 1 for i, x in enumerate("".join(bin(n + 256)[3:] for n in v)) if x == "1"]
[2, 4, 5, 12, 13, 17, 31, 32]

Notice the argument of enumerate is a generator, not a list. Same remark for the argument of join.

0

solved Expanding the inline python code [closed]