3

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

The function takes in this list and creates a bit string of length 64, where every index is a 0 except at the given indices.

So it would look like [0,0,....1,...1,..1,..0,0,0] where only at indices [34, 52, 57] we have ones.

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, maybe using lambda or map or itertools instead of enumerate.

Vajjhala
  • 160
  • 1
  • 15

2 Answers2

3

The problem with your approach is that you:

  • use an if statement for every bit; and
  • use the in test which can be rather expensive.

A 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 iterate only over the values of a, and you set these bits to 1.

Nevertheless it is a bit weird to encode this with a list of ints. A more compact way to do this is to encode this binary on an integer. For instance by using:

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

So in the last case if you set the bits like in your sample input, you obtain:

>>> bin(bit_string_gen([34, 52, 57]))
'0b1000010000000000000000010000000000000000000000000000000000'
>>> hex(bit_string_gen([34, 52, 57]))
'0x210000400000000'
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
2

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

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

Brian
  • 1,860
  • 1
  • 9
  • 14