MyCarta
MyCarta

Reputation: 818

Find if there are consecutive occurrences of an int in a list of ints

I am working on a Python online exercise.

The task is to:

Given an array of ints, return True if the array contains a 2 next to a 2 somewhere.

    has22([1, 2, 2]) → True
    has22([1, 2, 1, 2]) → False
    has22([2, 1, 2]) → False

The code I got so far:

def has22(nums):
  for i in range (len(nums)-1):
    if nums[i+1]==2 and nums[i]==2:
      return True
      break

will return all the True instances, but I cannot think of a way to include statement for the False instances (I would like to stick to a control flow solution). Any suggestions?

Upvotes: 1

Views: 268

Answers (2)

user2555451
user2555451

Reputation:

You can simplify your function by using any and a generator expression:

def has22(nums):
    return any(nums[i+1] == nums[i] == 2 for i in range(len(nums)-1))

Demo:

>>> def has22(nums):
...     return any(nums[i+1] == nums[i] == 2 for i in range(len(nums)-1))
...
>>> has22([1, 2, 2])
True
>>> has22([1, 2, 1, 2])
False
>>> has22([2, 1, 2])
False
>>>

Upvotes: 3

ig-melnyk
ig-melnyk

Reputation: 2879

You don't need break after return statement, and you just need to add "return False" statement inside your for loop

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

Upvotes: 3

Related Questions