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

标签 python

如何正确定义 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

关于python - 所以我试图回答这个 : Given a list of ints, 如果数组在某处包含 3 旁边的 3 则返回 True,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57734357/

相关文章:

python - pip install PIL 失败

python - 将图像转换为适当的尺寸 PyTorch

python - 多进程消息队列未接收消息

python - Paramiko 会被移植到 Python 3.x 吗?

python - 许多数据帧上的高效 Python Pandas Stock Beta 计算

python - Tensorflow 无法识别 cudart64_101.dll

Netbeans 中的 Python 引用外部模块

Python 估计数据拟合后的标准差

python - 更改 Tkinter 框架标题

python - 如何使python程序 ".py"可执行?