Bowen Liu
Bowen Liu

Reputation: 1127

Check if a certain sequence of numbers appears in an array. What's wrong with my thoughts?

I am learning the fundamentals of Python and doing some finger exercise. This one question is bogging me. I don't know where I did wrong. The question is this:

Given an array of ints, return True if the sequence of numbers 1, 2, 3 appears in the array somewhere.

My solution is:

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

I realize that this will give me False as long as the first 3 characters, so I change it to:

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

This time it works. I am wondering do I have to move the "return False" out of the sub-code section of the last if?

Thanks.

Upvotes: 0

Views: 525

Answers (2)

Sorin
Sorin

Reputation: 11968

Yes.

In the first solution if the first 3 ints are not what you are looking for you would stop. That's not what you want. You want to keep going and try other locations.

When you moved it out of the loop you are returning false only after you've checked all positions and none of them matched.

Upvotes: 1

ignoring_gravity
ignoring_gravity

Reputation: 10476

When you write

if nums[i:i+3] == arr1:
      return True
    else:
      return False

if the condition is not met, then the function stops executing and returns False.

Instead, you want the function to continue executing until it finds a triplet which satisfies that condition.

Upvotes: 1

Related Questions