我正在研究 Python online exercise .
任务是:
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
将返回所有 True 实例,但我想不出一种方法来包含 False 实例的语句(我想坚持控制流解决方案) .有什么建议吗?
请您参考如下方法:
你不需要在 return 语句之后中断,你只需要在你的 for 循环中添加“return False”语句
def has22(nums):
for i in range (len(nums)-1):
if nums[i+1]==2 and nums[i]==2:
return True
return False
