0

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.

2
  • 1
    Since you are accessing 3 numbers at a time, you only need to iterate till range(len(nums)-2). Commented Nov 15, 2020 at 2:39
  • Well, in your own words, what values of i will you create with each solution? What happens when you try to use i+2 to index into nums, when i is the largest possible value? Commented Nov 15, 2020 at 2:53

3 Answers 3

1

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

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

Comments

1

They have used len(num) -2 , so that the num [i+2] points to the last element and not a index outside of the num

Comments

1

Thats because you are checking i th , i+1 th and i+2 th elements in the loop. The requirement is to check 1,2,3 in the array anywhere. and in python indices starting at zero, so range(len(num)-2) makes it to iterate over 0 to 7, if it is 10 elements array.

Comments

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.