簡體   English   中英

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

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM