首页 > 解决方案 > 如何检查数组是否在 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。

标签: pythonfunctionloopsfor-loop

解决方案


这是解决此问题的另一种方法

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

推荐阅读