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

Not able to understand random.sample(range(1,40),3)) with sum(1<<i for i in random.sample(range(1,40),3))

I am trying to debug this piece of code and learn a little. I learn that it generates 3 unique values for i but how come the values of sum become this much big?

If I run it and debug it, it goes something like this. It keep changes since values are chosen randomly.

i = 6
i = 26
i = 38

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

test_num = 274945015872

Output:
100000000000100000000000000000001000000

Why the value for test_num 274945015872? It then uses this value to generate 39-bit binary string. Like how?

Can someone explain?

Here is the code:

test_num = sum(1<<i for i in random.sample(range(1,40),3))
#left to right one bit shifting
print (print (f"{test_num:039b}"))

>Solution :

this is how addition works …

  0b1000           8
+ 0b0100         + 4
---------       -----
  0b1100           12

each 1<<N creates an integer that has a binary value with exactly 1 ‘1’ and the rest zero

suming them sets all the one bits (a integer with 3 distinct bits set to ‘1’) if your indexes happen to be [0,1,2] you end up with the smallest possible value of 0b111 (7) but there are 40 total position 0..39 so it would be rare to get [0,1,2] as your output

as pointed out in the comments the sum can be replaced with

reduce(lambda x,y: x|y ,[i for i in ...])

this works because when you have a guarantee of distinct one positions NUMERIC ADDITION and BITWISE OR are identical operations

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