简体   繁体   中英

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?

I've tried this and it returns 8 as result:

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

*count is previously defined in the bigger algorithm I've implemented

Searching for the longest group of consecutive equal values can be done using 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

>>> 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

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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