0

I am doing a python course and ran into a problem that has me a bit confused on the logic. the problem is:

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

spy_game([1,2,4,0,0,7,5]) --> True
spy_game([1,0,2,4,0,5,7]) --> True
spy_game([1,7,2,0,4,5,0]) --> False

Here was my solution:

def spy_game(nums):
    code = ["x",0,0,7] #"x" at index 0
    for i in nums:
        if i == code[1]: # check if i matches seq index 1
            code.pop(1) # if True, remove i at seq index 1
    return len(code) == 1

However, this solution returned an error message:

IndexError                                Traceback (most recent call last)
<ipython-input-41-76ad0cd13e33> in <module>
      1 # Check
----> 2 spy_game([1,2,4,0,0,7,5])

<ipython-input-40-54389cdc3f5f> in spy_game(nums)
      2     code = ["x",0,0,7]
      3     for i in nums:
----> 4         if i == code[1]:
      5             code.pop(1)
      6     return len(code) == 1

IndexError: list index out of range

Here is the "correct" solution:

def spy_game(nums):
    code = [0,0,7,"x"] # "x" placed at index 3 instead
    for i in nums:
        if i == code[0]: # check i against sequence index 0
            code.pop(0)
    return len(code) == 1

I am having trouble understanding why my original solution failed. Why is index[1] "Out of range" when the list has indexes 0-3? What am I missing in the logic? Can anyone break it down? Thanks in advance.

2
  • 1
    You would be better off not altering a list while you are iterating through it. That's like trying to replace the wings of the plane you're flying in. Or some other analogy. Commented Mar 9, 2021 at 10:31
  • 1
    Once you remove all numbers from code list, you are left with list ['x'] whose length is one. Then you are trying to access its second element which causes IndexError. Commented Mar 9, 2021 at 10:39

1 Answer 1

1

You should write down what happens with code after each iteration of for i in nums.

You will find that after 0, 0, and 7 have been encountered, nums might still not be empty. 0, 0, and 7 will have been popped from code, leaving a list of length 1, making code[1] throw an IndexError at the next iteration.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, I get it now
Good! Could you mark the answer as accepted then?
I did but I get this message: "Thanks for the feedback! Votes cast by those with less than 15 reputation are recorded, but do not change the publicly displayed post score."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.