Here's the problem.
This is part of the List-2
Medium python list problems -- 1 loop.
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 was getting the error "list index is out of range" at first
I know where I was going wrong on line 4 of the original problem because once it is at the last number in the list it cannot add one anymore.
I have provided my original code below. The first code block was when I was getting the error "index out of range". The second solution works but I am wondering if there is a cleaner way of writing it.
Also on CodingBat when I run my solution it says "Other Tests" Failed at the bottom but no example I'm not sure what that means.
Thanks
Here's my code block - FIRST TRY:
def has22(nums):
for i in range(len(nums)):
first = nums[i]
second = nums[i+1]
if first == second:
return True
MY SOLUTION:
def has22(nums):
size = len(nums)
for i in range(len(nums)):
first = nums[i]
if size >= i+2:
second = nums[i+1]
if first == second:
return True
return False
So if the question is whether the solution can be written cleaner, I think something like this should work:
def has22(nums):
return (2, 2) in zip(num, num[1:])
and it looks pretty clean.
A little bit of explanation - zip
creates pairs of values from 2 lists, so I just slice the input list into 2, where in the second list I omit the first element. Then I simply check whether tuple 2, 2
exists in the zipped pairs.
BTW I just noticed a bug in your solution - it returns True
for input e.g. [2, 1]
(basically any input, where 2
is second to last. So to fix this bug, and preserve the original "idea" of your solution, you could write it like this:
def has22(nums):
for i, el in enumerate(nums):
if el == 2 and i + 1 < len(nums) and nums[i + 1] == 2:
return True
return False
enumerate
is the preferred way of iterating through a list with indices.
Эта статья взята из Интернета, укажите источник при перепечатке.
Если есть какие-либо нарушения, пожалуйста, свяжитесь с[email protected] Удалить.
я говорю два предложения