I have the following Python code below. I'm expecting the code to return True
but when I run it, it seems to always return False
. It seems to fail when checking if 361 is 361 but I can't work out why:
def comp(array1, array2):
if array1 is None or array2 is None or len(array1) is 0 or len(array2) is 0 or len(array1) is not len(array2):
return False
aListSquared = [x * x for x in sorted(array1)]
array2.sort()
print(aListSquared)
print(array2)
for x in range(len(aListSquared)):
print('{0}:{1}'.format(aListSquared[x], type(aListSquared[x])))
print('{0}:{1}'.format(array2[x], type(array2[x])))
if int(aListSquared[x]) is not int(array2[x]):
return False
return True
a1 = [121, 144, 19, 161, 19, 144, 19, 11]
a2 = [11 * 11, 121 * 121, 144 * 144, 19 * 19, 161 * 161, 19 * 19, 144 * 144, 19 * 19]
print(comp(a1, a2))
Can anyone tell me what i'm doing wrong or why the validation doesn't seem to be working correctly?
Many Thanks
In your lines
if array1 is None or array2 is None or len(array1) is 0 or len(array2) is 0 or len(array1) is not len(array2):
and
if int(aListSquared[x]) is not int(array2[x]):
you're using the is
operator to compare two integers. That's not how the operator should be used in Python: The operator is to test for object identity, yet you only want to find out if the value is the same. In your case, you should just use ==
instead of is
and !=
instead of is not
respectively.
For further reading, see the Python documentation on Value comparisons and Identity comparisons, as well as "is" operator behaves unexpectedly with integers for example.