Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
429 views
in Technique[技术] by (71.8m points)

Python: A program to find the LENGTH of the longest run in a given list?

Q: A run is a sequence of adjacent repeated values. Given a list, write a function to determine the length of the longest run. For example, for the sequence [1, 2, 5, 5, 3, 1, 2, 4, 3, 2, 2, 2, 2, 3, 6, 5, 5, 6, 3, 1], the longest run is 4.

I am having trouble with this, I've written a code that finds the longest run consist of the number '2' but have yet to get the length of the run which is 4.

Here is my code so far (i've commented out a part that i was working on but don't pay attention to it):

# 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()

Help please!!! :(((

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do this in one line using itertools.groupby:

import itertools
max(sum(1 for _ in l) for n, l in itertools.groupby(lst))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...