How to find the shortest identical consecutive sublist in a list with Python

4 Answers

0 votes
def shortest_identical_consecutive_sublist(lst):
    if not lst:
        return []

    shortest = None
    current = [lst[0]]

    for x in lst[1:]:
        if x == current[-1]:
            current.append(x)
        else:
            if shortest is None or len(current) < len(shortest):
                shortest = current
            current = [x]

    if shortest is None or len(current) < len(shortest):
        shortest = current

    return shortest


lst = [3, 3, 3, 7, 7, 7, 7, 7, 2, 2, 5, 5, 5, 5, 9, 9, 9, 9, 9, 9]

print(shortest_identical_consecutive_sublist(lst))


    
'''
run:
    
[2, 2]
    
'''

 



answered Feb 7 by avibootz
0 votes
def shortest_identical_consecutive_sublist(lst):
    runs = []
    current = [lst[0]]

    for x in lst[1:]:
        if x == current[-1]:
            current.append(x)
        else:
            if len(current) >= 2:
                runs.append(current)
            current = [x]

    if len(current) >= 2:
        runs.append(current)

    return min(runs, key=len) if runs else []


lst = [3, 3, 3, 7, 7, 7, 7, 7, 2, 2, 5, 5, 5, 5, 9, 9, 9, 9, 9, 9]

print(shortest_identical_consecutive_sublist(lst))


    
'''
run:
    
[2, 2]
    
'''

 



answered Feb 7 by avibootz
0 votes
from itertools import groupby

def shortest_identical_consecutive_sublist(lst):
    groups = [list(g) for _, g in groupby(lst)]
    
    return min(groups, key=len)


lst = [3, 3, 3, 7, 7, 7, 7, 7, 2, 2, 5, 5, 5, 5, 9, 9, 9, 9, 9, 9]

print(shortest_identical_consecutive_sublist(lst))


    
'''
run:
    
[2, 2]
    
'''

 



answered Feb 7 by avibootz
0 votes
from itertools import groupby

def shortest_identical_consecutive_sublist(lst):
    groups = [list(g) for _, g in groupby(lst)]
    groups = [g for g in groups if len(g) >= 2]
    
    return min(groups, key=len) if groups else []


lst = [3, 3, 3, 7, 7, 7, 7, 7, 4, 4, 5, 5, 5, 5, 9, 9, 9, 9, 9, 9]

print(shortest_identical_consecutive_sublist(lst))


    
'''
run:
    
[4, 4]
    
'''

 



answered Feb 7 by avibootz

Related questions

...