gpt4 book ai didi

python - 查找整数列表中是否连续出现一个整数

转载 作者:太空宇宙 更新时间:2023-11-04 08:07:49 25 4
gpt4 key购买 nike

我正在研究 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

关于python - 查找整数列表中是否连续出现一个整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28035004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com