Find the longest unbreakable shared items in a list

I have this list that only contains Ws and Ss:

ls = ['W', 'S', 'S', 'S', 'W', 'W', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'W', 'W', 'W', 'W', 'W', 'W', 'S'] 

      

What I want to do is extract the longest non-intercepting "S" in this list? and return the index of that Ss, returning:

['S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S']

      

and

[6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

      

How can I achieve this?

+3


source to share


5 answers


Use itertools.groupby

with enumerate

and max

:



>>> from operator import itemgetter
>>> from itertools import groupby
>>> val = max((list(g) for k, g in
                   groupby(enumerate(ls), itemgetter(1)) if k == 'S'), key=len)
>>> indices, items = zip(*val)
>>> indices
(6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)
>>> items
('S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S')

      

+11


source


Same solution as Ashwini Chaudhary minus the elegance,



from itertools import groupby

index, result, m_index = 0, [], 0

# Group based on the elements of the list
for item, grp in groupby(ls):
    # Get the grouped items as a list
    grp = list(grp)
    # Filter out `M`s and check if this is the biggest run of `S`s ever seen
    if item == "S" and len(grp) > len(result):
        result, m_index = grp, index
    # Increment the index to keep track of the list covered
    index += len(grp)

print(result, list(range(m_index, m_index + len(result))))

      

+3


source


>>> import re
>>> max((x.group(), x.span()) for x in re.finditer("S+", "".join(ls)))
('SSSSSSSSSSS', (6, 17))

>>> range(6, 17)
[6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

      

+3


source


package com.algo.sort;

public class LargestCont {

static int g[]={1,1,1,1,2,2,3,4,5,5,5,5,5,5,5,5,5,5,5,2,2,2,2,3,3,3,3,3,3,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,3,3,3,3,3,3,3,3,3,0,0,0,0,0,0,0,0,0};


public static void main(String f[]){
    manage(g);
}


public static void manage(int[] j){
    int max=1; int val=-1; int count=0; int ans=0;
    for(int i=0;i<j.length;i++){
        if(j[i]!=val){
            if(max>count){
                ans=val;
                count=max;
                System.out.println(ans+"...."+count);                   
            }
        val=j[i]; max=1;}else{
            max++;
        }                   
    }

    System.out.println(ans);

}

      

}

-1


source


ls = ['W', 'S', 'S', 'S', 'W', 'W', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'W', 'W', 'W', 'W', 'W', 'W', 'S']
for x,y in enumerate(ls):
    print (x,str(y).split("W"))

      

I found this.

-2


source







All Articles