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

后端 未结 6 2307
南方客
南方客 2020-12-03 12:59

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,

6条回答
  •  悲&欢浪女
    2020-12-03 13:17

    Just another way of doing it:

    def longestrun(myList):
        sett = set()
        size = 1
        for ind, elm in enumerate(myList):
            if ind > 0:
                if elm == myList[ind - 1]:
                    size += 1
                else:
                    sett.update([size])
                    size = 1
        sett.update([size])
        return max(sett)
    
    myList = [1, 2, 5, 5, 3, 1, 2, 4, 3, 2, 2, 2, 2, 3, 6, 5, 5, 6, 3, 1]
    print longestrun(myList)
    

提交回复
热议问题