Python beginner – Question on for-loop iteration

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.

Answer

thats not exactly an amazing solution either, this would be proper:

def array123(nums):
  for i in range(len(nums)-2):
    if nums[i:i+3] == [1,2,3]:
      return True
  return False

print(array123([1,2,3]))
True

the main differences between your code and codingbat’s is how the range is used

your range is the length of the list right? so since you are adding to the index by 2 at the highest case, we only should iterate until the length – 2, because anything over reaches past the highest index

Leave a Reply

Your email address will not be published. Required fields are marked *