Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading