Home > database >  Is there a faster way I can calculate binary operation in python?
Is there a faster way I can calculate binary operation in python?

Time:02-24

Suppose I have a binary string: z = abc, where a,b,c are either 0 or 1, so we can convert c into an integer from 0 to 7. Now I want to give a,b,c another 'layer' of value, where a = 1/2^1 = 1/2, b = 1/2^2 = 1/4, c = 1/2^3 = 1/8. My goal is to create a dictionary, where the keys are integers 0-7, and values are the associated calculations based on a,b,c values.

The only way I'm able to solve this question is to 'brute force' the results. For example, when the key is 5 (z = 101), the value would be 1/2 0 1/8 = 5/8, and perform all calculations manually, then append the item to the dictionary. Is there a tool / method in python that will allow me to create the calculation faster? I really have no idea how I can do that. Any suggestions / help is appreciated.

CodePudding user response:

One naïve approach would be to iterate over the bit-string, and multiply each bit by the matching power of 0.5:

res = 0
for i, bit in enumerate(z, 1):
    res  = int(bit) * 0.5**i

For z = "101" this will give res as 0.625 which is 5/8


Could be compacted using sum:

res = sum(int(bit) * 0.5**i for i, bit in enumerate(z, 1))

If z is actually an integer, just change the zs above to format(z, 'b') to get its binary string representation.

CodePudding user response:

Just to elaborate on my comment a bit:

for key, value in {bin(key)[2:]: key/8 for key in range(8)}.items():
    print(f"{key:>3}: {value}")

Output:

  0: 0.0
  1: 0.125
 10: 0.25
 11: 0.375
100: 0.5
101: 0.625
110: 0.75
111: 0.875
>>> 

Is this the output you're looking for?

  • Related