Reputation: 2148
Would like to count a binary value of integers until a 1 is reached. Then return an integer, not a list.
binary = bin(1)[2:].zfill(8)
# 00000001
zeros = [x for x in binary] # .. Count zeros... Until 1
print(zeros) # Expected 7 integer, not type <class 'list'> = 7 until 1
# ['0', '0', '0', '0', '0', '0', '0', '1']
Input: 00000001
Expected Output: 7
Upvotes: 1
Views: 371
Reputation: 8962
So I guess I'll post my answer as a comment, as requested by OP.
First:
zeros.count("0")
Of course, we could make this a bit more general. Consider any binary number, padded with zeros to some width:
>>> b = f"{19:010b}"
>>> b
'0000010011'
You could then take this binary string and split it on "1"
:
>>> b.split("1")
['00000', '00', '', '']
Then find all counts of contiguous zeros:
>>> [s.count("0") for s in b.split("1")]
[5, 2, 0, 0]
You could then filter out the counts of 0
, since those correspond to areas where there were contiguous 1
bits...
I dunno I feel like not enough information was given so this could really go in so many directions!
Upvotes: 1