python - 一个集合中至少有 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 个问题!
解决方案
&
是按位与运算符,而不是逻辑运算符。您正在寻找的是这样的条件:
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
推荐阅读
- python - 在python中保持对象静态
- android - 如何格式化字符串以在 PDF 中打印新行 - 无法正确打印新行 - Kotlin
- java - Kubernetes 和 JVM 内存设置
- javascript - 正则表达式条件搜索 javascript
- vb.net - 在字符串中查找单词的所有实例并将它们显示在文本框中(vb.net)
- airflow - xcom 值被 if/else 循环中的 else 语句覆盖
- java - 如何绘制方法的分解和组合?
- android - 如何从 Android 的主屏幕访问触摸屏信息
- ruby-on-rails - Rails 模型(或变量)是否可以保存在服务器内存中并可供所有会话/作业使用?
- python - kivy 中没有名为“numpy.core._multiarray_umath”的模块