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.
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.