Find maximum length of consecutive repeated numbers in a list

前端 未结 2 612
感动是毒
感动是毒 2021-01-14 23:23

My question is how to find the maximum length of consecutive repeated numbers (or elements in general) in a list. I wrote the following function which works fine but I was w

相关标签:
2条回答
  • 2021-01-15 00:01

    You can use itertools.

    In [8]: import itertools
    
    In [9]: z = [(x[0], len(list(x[1]))) for x in itertools.groupby(a)]
    
    In [10]: z
    Out[10]: [(1, 2), (2, 3), (3, 1)]
    

    Tuples are in (item, count) format. If there are multiple runs of a given number, this will group them accordingly as well. See below.

    In [11]: a = [1,1,1,1,1,2,2,2,2,2,1,1,1,3,3]
    
    In [12]: z = [(x[0], len(list(x[1]))) for x in itertools.groupby(a)]
    
    In [13]: z
    Out[13]: [(1, 5), (2, 5), (1, 3), (3, 2)]
    

    Getting the max value isn't that hard from here.

    In [15]: max(z, key=lambda x:x[1])[1]
    Out[15]: 5
    
    0 讨论(0)
  • 2021-01-15 00:27
    longest_fragment = 0
    current_fragment = 0
    
    a = int(input())
    last_input = a # why do I assign last_input here?
    while a:
        if a == last_input:
            current_fragment += 1
        else:  # why is current_fragment assigned 1 in this clause?
            if current_fragment > longest_fragment:
                longest_fragment = current_fragment
                current_fragment = 1
        last_input = a
        a = int(input())
    
    longest_fragment = max(longest_fragment, current_fragment) 
    # why didn't i use max in the loop?
    # why am I checking again down here anyway?
    
    print('The longest fragment was:', longest_fragment)
    
    0 讨论(0)
提交回复
热议问题