首页 > 解决方案 > 一个集合中至少有 3 个连续偶数的列表中的集合总数?

问题描述

如果我有一个整数列表,并且我想在该列表中找到集合的总数,其中集合至少是 3 个连续的偶数?

例如: list1 = [1,2,4,6,8,11,2,8] 有 1 个这样的集合,因为只有 1 个集合 (2,4,6,8) 具有至少 3 个连续的偶数

我的做法:

list1 = [1,2,4,6,8,11,2,8]
SetofEven = 0
for i in range(0,len(list1)-2):
    a, b, c = list1[i:i+3]
    if a%2 == b%2 == c%2 == 0:
        SetofEven = SetofEven + 1

第一次我想找到只有 3 个连续偶数的集合,然后以此为基础。不知道如何解决至少 3 个问题!

标签: pythonlistnumbers

解决方案


&按位与运算符,而不是逻辑运算符。您正在寻找的是这样的条件:

if a % 2 == b % 2 == c % 2 == 0

或像这样:

if a % 2 == 0 and b % 2 == 0 and c % 2 == 0

与 C++ 等语言相反,在 Python中逻辑AND 使用运算符,而您使用.&&and

编辑:关于问题的第二部分,我认为这种方法不会有成效,因为这样的循环显示了长度为 3 的重叠序列。你可能会更好地使用itertools.groupby

from itertools import groupby

# list of pairs (True/False, list of numbers)
groups = groupby(list1, lambda x: x % 2 == 0)

count = 0
for even, sequence in groups:
    if even and len(list(sequence)) >= 3:
        count += 1

groupby根据谓词对序列进行分组,因此对于

>>> list1 = [1, 2, 4, 6, 8, 11, 2, 8]
>>> list(groupby(list1, lambda x: x % 2 == 0))
[(False, [1]), (True, [2, 4, 6, 8]), (False, [11]), (True, [2, 8])]
# actually the second elements in pairs are not lists but iterators, but their contents are the same

推荐阅读