Skip to content Skip to sidebar Skip to footer

How To Count The Longest Sequence Of The Same Value In A List Of Lists, And Then Output The Largest Sequence In A Tuple

I have a list of lists of lists 9in a text file) with values similar to what is below: L = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1

Solution 1:

You can do this simply with itertools.groupby():

In []:
import itertools as it

[(k, sum(1 for _ in g)) for k, g in it.groupby(L)]
# [(k, len(list(g)) for k, g in it.groupby(L)]  # alternative

Out[]:
[(1, 112), (0, 394), (1, 65), (2, 359), (1, 71)]

To get the maximum, you can use max() with a key, e.g.:

In []:
import operator as op

counts = [(k, sum(1 for _ in g)) for k, g in it.groupby(L)]
max(counts, key=op.itemgetter(1))

Out[]:
(0, 394)

However, fixing your code.

  • You are confusing your indexing (counter), when you reset it in the else: block you start from the beginning again. Just use range(1, len(l)) in your for loop for the index.
  • You don't reset sl in the else: block (hence it keeps growing by 111) but you really don't need to create the sl list just count the items
  • You miss the case of the last value
  • Dealing with the last value needs a little reordering of logic

So fixed, it would look like:

def longest_sequence(l):
    counter = 1
    sublists = []
    for i in range(1, len(l)):
        if l[i] != l[i-1]:
            sublists.append([l[i-1], counter])
            counter = 0
        counter += 1

    if counter > 0:
        sublists.append((l[i], counter))

    return sublists

In []:
longest_sequence(L)

Out[]:
[(1, 112), (0, 394), (1, 65), (2, 359), (1, 71)]

In []:
max(longest_sequence(L), key=op.itemgetter(1))

Out[]:
(0, 394)

Solution 2:

You can use a run length encoding algorithm. Example tool from the more_itertools library:

Code

import more_itertools as mit    


list(mit.run_length.encode(L))
# [(1, 112), (0, 394), (1, 65), (2, 359), (1, 71)]

Details

The .encode method returns the equivalent of following generator expression:

((k, ilen(g)) for k, g in groupby(iterable))

You can optionally use the .decode method to get back the original list.

Install via > pip install more_itertools.

Post a Comment for "How To Count The Longest Sequence Of The Same Value In A List Of Lists, And Then Output The Largest Sequence In A Tuple"