I'm looking for the fastest way ( O(n^2) not acceptable) to apply the AND operator in more than 2 numbers in Python .
There are two scenarios:
a) at the input we have numbers in the range between M and N
b) there can be a set of any natural numbers
Currently, my code uses & operator in a loop that always calculates the bit of the result (even though we know that if we have 0 , then the next and all subsequent bits of the result will always be 0 ). One of my ideas is to calculate the bits in the columns, and for this column, stop calculating when there is 0 , because the result bit will be 0 .
Example (included in the test code below)

Existing (iterative), rather slow ( O(n^2) ) code:
def solution(M, N): result = M for x in xrange(M, N): result &= x return result def solution_sets(N): result = N[0] for x in N: result &= x return result print solution(5, 7)
It would be nice if this solution were expanded to, for example, the XOR operator.
I ask for some ideas on how to start implementing this in Python and maximize performance.
Thanks!
source share