Python:一个程序,用于查找给定列表中运行时间最长的LENGTH?

use*_*327 6 python sequence python-3.x

问:运行是一系列相邻的重复值.给定一个列表,编写一个函数来确定最长运行的长度.例如,对于序列[1,2,5,5,3,1,2,4,3,2,2,2,3,3,5,5,6,3,1],最长跑是4.

我遇到了麻烦,我写了一个代码,发现最长的运行由数字'2'组成,但还没有得到运行的长度为4.

这是我到目前为止的代码(我已经注释掉了我正在研究的部分,但是没有注意它):

# longestrun.py
#   A function to determine the length of the longest run
#   A run is a sequence of adjacent repeated values.

def longestrun(myList):
    result = None
    prev = None
    size = 0
    max_size = 0


    for i in myList:
        if i == prev:
            size += 1
            if size > max_size:
                result = i
                max_size = size
        else:
            size = 0
        prev = i
    return result



def main():
    print("This program finds the length of the longest run within a given list.")
    print("A run is a sequence of adjacent repeated values.")

    myString = input("Please enter a list of objects (numbers, words, etc.) separated by
    commas: ")
    myList = myString.split(',')

    longest_run = longestrun(myList)

    print(">>>", longest_run, "<<<")

main()
Run Code Online (Sandbox Code Playgroud)

请帮忙!!!:(((

Dav*_*son 12

您可以使用一个行做到这一点itertools.groupby:

import itertools
max(sum(1 for _ in l) for n, l in itertools.groupby(lst))
Run Code Online (Sandbox Code Playgroud)