Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find if the array contain a 2 next to a 2

I am stuck on this problem

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

I know the basic idea (there are syntax errors) but I can't implement it. I would also like to know what type of problem this is, eg. graph, search?

def has22(nums):
for x in nums:
    if ( (nums[x] = 2) and (nums[x+1] = 2) )
        return True

return False 
like image 410
user2284926 Avatar asked May 29 '13 11:05

user2284926


1 Answers

def has22(nums):
    return any(x == y == 2 for x, y in zip(nums, nums[1:]))

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

In Python 2 use: from itertools import izip if you want a lazy zip

like image 137
jamylak Avatar answered Oct 29 '22 14:10

jamylak