[英]How to find the longest sequence of equal elements in a sequence?
我有一个清单,例如:
test_list = [1, 43, 23, 4, 4, 4, 4, 4, 4, 2, 4, 4]
数字4
的最大序列组成6
项目,我该如何实现一个算法来计算这个?
我已经尝试过了,它返回 8 作为结果:
for item in test_list:
if item == 4:
count += 1
*count 之前在我实现的更大算法中定义
可以使用itertools.groupby
& max
搜索最长的连续相等值组
>>> from itertools import groupby
>>> test_list = [1, 43, 23, 4, 4, 4, 4, 4, 4, 2, 4, 4]
>>> max([list(group) for _, group in groupby(test_list)], key=len)
[4, 4, 4, 4, 4, 4]
如果我们需要最长的连续4
s 组——我们可以按项目过滤,例如
>>> max([list(group) for item, group in groupby(test_list) if item == 4], key=len)
[4, 4, 4, 4, 4, 4]
max_len = -1 count = 0 for x in test_list: if x == 4: count += 1 else: if count > max_len: max_len = count count = 0
它可能不是最 Python 或最聪明的代码,但它应该可以工作
test_list = [1, 43, 23, 4, 4, 4, 4, 4, 4, 2,1,4,4]
max_seq=0
count=1
for index, item in enumerate(test_list):
if index < len(test_list)-1:
if item == test_list[index+1]:
count += 1
print(count)
else:
if count > max_seq:
max_seq = count
count = 1
print('longest sequence: ' + str(max_seq))
可能有几种方法可以做到这一点,但这里有一个想法。 这特别是如果您试图找到一般最长的序列,而不是数字 4 的最长序列。
longest_val <- 0
longest_count <- 0
prev_item <- Null
count <- 0
for all items in list
if item == prev_item
count++
if count > longest_count
longest_count <- count
longest_val <- item
else
count <- 0
prev_item <- item
(PS 这是伪代码,不是 Python)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.