Find if the array contain a 2 next to a 2
Solution 1
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
Solution 2
def has22(nums):
for x in range(len(nums)-1):
if (nums[x] == 2) and (nums[x+1] == 2):
return True
return False
I have just corrected your code. It runs in linear time so don't see any reason to work on it further.
Here is the running code on codebunk. http://codebunk.com/bunk#-Ivk7Xw2blX3cIWavI17
Solution 3
def has22(nums):
it = iter(nums)
return any(x == 2 == next(it, None) for x in it)
>>> has22([1, 2, 2])
True
>>> has22([1, 2, 1, 2])
False
>>> has22([2, 1, 2])
False
Solution 4
def has22(nums):
for i in range(len(nums) - 1):
if nums[i] == 2 and nums[i + 1] == 2:
return True
return False
This was the simplest solution I came up with.
Using a for loop to check if the iterated number, nums[i] == 2
"and" the one very next to it, [i+1] == 2
as well.
(len(nums)-1)
: this line prevents it from going out of the range through the for loop as the i+1
on the final loop will check out of the range.
Solution 5
def has22(nums):
return '22' in ''.join(map(str, nums))
list [1, 2, 2] -> str '122'
return '22'
in '122'
user2284926
Updated on June 11, 2022Comments
-
user2284926 about 2 years
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