Skip to main content
 首页 » 编程设计

python之所以我试图回答这个 : Given a list of ints, 如果数组在某处包含 3 旁边的 3 则返回 True

2025年05月04日14Leo_wl

如何正确定义 y?

我已经尝试过明确地将 y == 0 放在 for 循环的内部和外部

def has_33(nums): 
 
    for x in nums: 
 
        if nums[0] != 3: 
            y == 0 
 
        if x == 3: 
            y = index(x) 
 
        if nums[y+1] == 3: 
            return True 
 
        else: 
            return False 

has_33(1,2,2,3,2,2,3,3) 例如应该返回 true

请您参考如下方法:

我不会使用列表作为可迭代对象,而是使用带有索引的 for 循环。这应该可以大大简化逻辑:

def has_double_3(nums): 
    # Start at the second element, and look at indices i, i-1 
    for i in range(1, len(nums)): 
        if nums[i - 1] == nums[i] and nums[i] == 3: 
            # found two numbers in a row equal to 3 
            return True 
 
    # no match found return false 
    return False