0

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

finefoot
  • 9,914
  • 7
  • 59
  • 102
  • 2
    As an aside, you can shorten up that first `if` leveraging the fact that `None` and an empty array are both falsey. `if not(array1 or array2) or (len(array1) != len(array2)):`. That clears up some the of the problems with `is` while you are at it – tdelaney Feb 19 '20 at 00:02
  • 2
    side note...just check for empty list or length of list for 0..meaning just do either `if not array1 or array2:` this implies checking for whether the list is empty or not so that way you can skip checking the `len(array1) or len(array2) is 0` :) – de_classified Feb 19 '20 at 00:04

3 Answers3

5

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.

finefoot
  • 9,914
  • 7
  • 59
  • 102
2

This syntax

if int(aListSquared[x]) is not int(array2[x]):

is not the same as

if int(aListSquared[x]) != int(array2[x]):

please refer to this Python != operation vs "is not"

Errol
  • 600
  • 4
  • 16
1

Rewriting this expression:

if int(aListSquared[x]) is not int(array2[x]): return False

with this:

if int(aListSquared[x]) != int(array2[x]): return False

The code returns True.