Find maximum length of consecutive repeated numbers in a list

前端 未结 2 616
感动是毒
感动是毒 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: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)
    

提交回复
热议问题