I tried solving the question below on codingbat:
"Given an array of integers, return True if the sequence of numbers 1, 2, 3 appears in the array somewhere".
This was my solution which returned with the error "index out of range":
def array123(nums):
for i in range(len(nums)):
if nums[i]==1 and nums[i+1]==2 and nums[i+2]==3:
return True
return False
This was Codingbat's solution:
def array123(nums):
for i in range(len(nums)-2):
if nums[i]==1 and nums[i+1]==2 and nums[i+2]==3:
return True
return False
I know I'm missing a trick here. Please could someone explain why I have to iterate over range(len(nums)-2)??
Thank you.
range(len(nums)-2).iwill you create with each solution? What happens when you try to usei+2to index intonums, wheniis the largest possible value?