I have a list of integers, e.g. i=[1,7,3,1,5]
which I first transform to a list of the respective binary representations of length L
, e.g. b=["001","111","011","001","101"]
with L=3
.
Now I want to compute at how many of the L
positions in the binary representation there is a 1
as well as a zero 0
. In my example the result would be return=2
since there is always a 1
in the third (last) position for these entries. I want to compute this inside a function with a numba decorator.
Currently my code is:
@nb.njit
def count_mixed_bits_v2(lst):
andnumber = lst[0] & lst[1]
ornumber = lst[0] | lst[1]
for i in range(1, len(lst)-1):
andnumber = andnumber & lst[i+1]
ornumber = ornumber | lst[i+1]
xornumber = andnumber ^ ornumber
result = 0
while xornumber > 0:
result += xornumber & 1
xornumber = xornumber >> 1
return result
First I take the AND of all numbers, ans also the OR of all numbers, then the XOR of those two results will have a 1 where the condition is fulfilled. In the end I count the number of 1's in the binary representation. My code seems a bit lengthy and I'm wondering if it could be more efficient as well. Thanks for any comment!
Edit: Without the numba decorator the following function works:
def count_mixed_bits(lst):
xor = reduce(and_, lst) ^ reduce(or_, lst)
return bin(xor).count("1")
(Credit to trincot)