Home > OS >  Why is it that if I swap the position of two conditions with an 'and' operator in between
Why is it that if I swap the position of two conditions with an 'and' operator in between

Time:08-11

So I'm doing an exercise called missing number and I don't understand why this statement causes a list index out of range error.

if nums[i] != nums[j] and nums[i] < len(nums):

But when I use this condition the code works:

if nums[i] < len(nums) and nums[i] != nums[j]:

Aren't these two lines of code functionally the exact same? I was thinking maybe it's an order of precedence issue but even after I wrapped the it in brackets there was still an out of range error.

Here is the full code below:

 def missingNumber(self, nums: List[int]) -> int:
    i, n = 0, len(nums)
    while i < n:
        j = nums[i]
        if nums[i] != nums[j] and nums[i] < n:
            nums[i], nums[j] = nums[j], nums[i]
        else:
            i  = 1
    
    for i in range(n):
        if i != nums[i]:
            return i
        
        
    

CodePudding user response:

Boolean operators in Python use short-circuiting logic, which means that if the first condition of the and is falsey, the second condition will not be checked. As a result, the order of the conditions is significant.

In your example, since nums[i] is part of both conditions, we can conclude that the IndexError is coming from nums[j]. We can also conclude that, for your input data, whenever nums[i] < n, j is always in range. However, that may not hold for all inputs, so you should fix your logic to only check the value of nums[j] if j < len(nums).

  • Related