简体   繁体   English

如何在序列中找到最长的相等元素序列?

[英]How to find the longest sequence of equal elements in a sequence?

I have a list such as:我有一个清单,例如:

test_list = [1, 43, 23, 4, 4, 4, 4, 4, 4, 2, 4, 4]

The greatest sequence of the number 4 makes up 6 items, how can I implement an algorithm to count this?数字4的最大序列组成6项目,我该如何实现一个算法来计算这个?

I've tried this and it returns 8 as result:我已经尝试过了,它返回 8 作为结果:

for item in test_list:
  if item == 4:
    count += 1

*count is previously defined in the bigger algorithm I've implemented *count 之前在我实现的更大算法中定义

Searching for the longest group of consecutive equal values can be done using itertools.groupby & max可以使用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]

If we need the longest group of consecutive 4 s -- we can filter by item like如果我们需要最长的连续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

It's probably not the most pythonic or smartest code however it should work它可能不是最 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))

There's probably a few ways you could do this, but here's one idea.可能有几种方法可以做到这一点,但这里有一个想法。 This is specifically if you are trying to find the longest sequence in general, not the longest sequence of the number 4.这特别是如果您试图找到一般最长的序列,而不是数字 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 This is pseudocode, not Python) (PS 这是伪代码,不是 Python)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM