Search code examples
pythonnumpynumbabinary-operators

List of binary numbers: How many positions have a one and zero


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 would be happy for any comment. I think, ideally I should do many Xor operations at the same time. However, I'm not sure how I can do this efficiently.

Edit: Thanks for the many answers!! I have to check which one is the fastest.


Solution

  • One observation is that if you take the AND of all numbers, and also the OR of all numbers, then the XOR of those two results will have a 1 where the condition is fulfilled.

    So:

    from functools import reduce
    from operator import and_, or_
    
    def count_mixed_bits(lst):
        xor = reduce(and_, lst) ^ reduce(or_, lst)
        return bin(xor).count("1")
    
    
    count_mixed_bits([1,7,3,1,5])  # 2