1

For the following exercise I am expecting an IndexError for certain test inputs, but it is not occurring.

Goal: Write a function that takes in a list of integers and returns True if it contains 007 in order

My Function:

def spy_game(nums):
    for x in range(len(nums)):
        print(x)
        try:
            if nums[x]==0 and nums[x+1]==0 and nums[x+2]==7:
                return(True)
        except IndexError:
            return(False)

Test Cases:

#Case 1
    spy_game([1,2,4,0,0,7,5])
#Case 2
    spy_game([1,0,2,4,0,5,7])
#Case 3
    spy_game([1,7,2,0,4,5,0])

Question: I included the print statement in the function to try to understand the issue. Case 1 prints 0 1 2 3 and returns True which is expected. Case 2 prints 0 1 2 3 4 5 6 and does not return anything. Case 3 prints 0 1 2 3 4 5 6 and returns False. For both Case 2 and 3 I would expect it to print up to 5 and at that point result in an IndexError. I am not sure why Case 2 reaches 6 and has no IndexError and why Case 3 reaches 6 and does have one. Thanks in advance!

metro
  • 508
  • 2
  • 9
Ian G
  • 13
  • 2

1 Answers1

1

The reason it is not giving you an IndexError comes from how and operations occur in the code. Case 2 will not get to the point of looking for x+2 because it fails on the other operations before.

a = [True, True, True]
if a[0] == False and a[100000] == None:

for example, will never give you an IndexError because it fails on the first if.

Arson 0
  • 757
  • 2
  • 14
  • 1
    Yes, this makes sense and I have linked this question to another about short-circuiting. Thanks so much! – Ian G Jan 17 '22 at 02:02