Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!!! :(((

like image 889
user3386327 Avatar asked Mar 06 '14 03:03

user3386327


People also ask

How do you find the length of a long string in a list Python?

Use max() to find the longest string in a list. Call max(a_list, key=len) to return the longest string in a_list by comparing the lengths of all strings in a_list .


1 Answers

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))
like image 99
David Robinson Avatar answered Sep 20 '22 04:09

David Robinson