Formation of fast bit strings taking into account indices

Here a is a list, for example [34, 52, 57]

.

The function takes this list and creates a bit string of length 64, where each index is 0 except for the specified indexes.

So it will look like [0,0,....1,...1,..1,..0,0,0]

where only with the indices [34, 52, 57]

we have.

def bit_string_gen(a):

    bit_string = []
    for key, value in enumerate(range(64)):
        if key in a:
            bit_string.append(1)
        else:
            bit_string.append(0)

    return bit_string

      

Is there a better way to do this, perhaps using lambda

or map

or itertools

instead enumerate

.

+3


source to share


2 answers


If you're looking for a solution using map / lambda, here's the one-liner:



map(lambda x: 1 if x in [34, 52, 57] else 0, range(0, 64))

+2


source


The problem with your approach is that you:

  • use an instruction if

    for each bit; and
  • use a test in

    that can be quite expensive.

The beter method can be:

def bit_string_gen(a):
    bit_string = [0]*64
    for value in a:
        bit_string[value] = 1
    return bit_string

      

So, here you are only iterating over the values a

and you are setting those bits to 1

.



However, it's a bit weird to code this with a int

s list . A more compact way to do this is to encode this binary to an integer. For example using:

def bit_string_gen(a):
    bit_string = 0
    for value in a:
        bit_string |= 1 << value
    return bit_string

      

So in the latter case, if you set the bits as in your example input, you get:

>>> bin(bit_string_gen([34, 52, 57]))
'0b1000010000000000000000010000000000000000000000000000000000'
>>> hex(bit_string_gen([34, 52, 57]))
'0x210000400000000'

      

+3


source







All Articles