سؤال

I am having a problem with an xor search. I have an array composed of binary values. My list contains 1000 distinct binary values, and I want to time how long it takes for a double loop to find an element in the list. Therefore for a double loop search, I expect it to go through the loop [(1) + (2) +(3)+...+(1000)] = 500500 times. [n(n+1) / 2]

I use the bitwise_xor in the following code

from numpy import bitwise_xor

count = 0
for word1 in listOutTextnoB:
    for word2 in listOutTextnoB:
        count+=1
        if bitwise_xor(word1,word2)==0:
            break
print "count"

Unfortunately, when I print count, I get count = 1,000,000

If I change the if statement to

if bitwise_xor(word1,word2):
      break

count is 1000

I also tried to do:

if word1^word2==0:
       break

but it gives me "TypeError: unsupported operand type(s) for ^: 'str' and 'str'"

A working example would be: 1101110111010111011101101110110010111100101111001 XOR 1101110111010111011101101110110010111100101111001 it should give me 0 and exit the inner loop

What is wrong with code?

هل كانت مفيدة؟

المحلول

^ works on integers, not arrays, so that is not surprising.

I don't know why you used strings but:

from numpy import bitwise_xor

listOutTextnoB = range(1000)
count = 0
for word1 in listOutTextnoB:
    for word2 in listOutTextnoB:
        count+=1
        if bitwise_xor(word1,word2)==0:
            break
print "count", count

prints

count 500500

as you predict.

EDIT: yes, you should be doing

if int(word1) ^ int(word2) == 0:
    break

bitwise_xor is actually returning 'NotImplemented' for every string, string input.

نصائح أخرى

Your error shows the problem: the values in your list are strings, not numbers. I'm not sure what bitwise_xor does to them, but I'm pretty sure it won't convert them to numbers first. If you do this manually (bitwise_xor (int (word1), int (word2))), I think it should work.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top