python - 如何检查数组是否在 3 旁边包含 3?
问题描述
我需要找出一个整数数组是否在 3 旁边包含一个 3。
这是我目前拥有的代码:
def has_33(nums):
for i in nums:
if i== 3:
if abs(nums[i]-nums[i+1:-1])==0:
print(True)
else:print(False)
else:pass
它给了我以下错误:
nums[i+1] 不在范围内
这些是我的测试用例:
has_33([ 3, 1, 3]) # i want output true for this list
has_33([1, 3, 1, 3]) # true
has_33([1, 3, 2]) # false
has_33([4, 2, 3, 3, 2]) # true
has_33([1, 3, 3, 1]) # true
我想找到列表中的前 3 个。如果在前 3 个之后的列表中还有另外 3 个,那么我想打印 true,否则我想打印 false。
解决方案
这是解决此问题的另一种方法
def has_33(array):
threes = [] #create an array to store threes
for x in array:
if x == 3:
threes.append(x) #if number is three, append it to array
if len(threes) > 1: #check if length of array is greater then 1
return True
else:
return False
print(has_33([1,3,8,3,3,5])) #returns True
print(has_33([1,3,8,2,1,5])) #returns False
推荐阅读
- laravel - 日期比较不考虑时区
- go - grpc server stops receiving messages after sending many messages simultaneously
- azure-devops - 启用自包含导致 dotnet 发布失败并使用私有 NuGet
- javascript - 400 error "You must pass a valid patch document in the body of the request."
- java - 检测 java web 应用程序中 cpu 使用率 15% 的原因
- python - 地理围栏根据距离和方位计算新的经度、纬度(Python - 库)
- azure - Can we copy Azure blobs from one storage account to other storage accounts in parallel from same machine?
- java - to disconnect the call programmatically in android for devices above Marshmallow
- java - 在 Sikuli 和 Selenium 之间切换时,如何导航到 Selenium 上一个会话中打开的确切页面?
- javascript - Angular 父子绑定更改检测