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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…