Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,844 questions

51,765 answers

573 users

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 12 hours ago 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 12 hours ago 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 11 hours ago 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 11 hours ago by avibootz
...