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

后端 未结 6 2200
南方客
南方客 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:14

    This should work if you do not want to use itertools and imports.

    a=[1, 2, 5, 5, 3, 1, 2, 4, 3, 2, 2, 2, 2, 3, 6, 5, 5, 6, 3, 1]
    
    def longestrun(myList):
        result = None
        prev = None
        size = 0
        max_size = 0
    
    
        for i in myList:
            if i == prev:
                print (i)
                size += 1
                if size > max_size:
                    print ('*******  '+ str(max_size))
                    max_size = size 
            else:
                size = 0
            prev = i
        print (max_size+1)    
        return max_size+1
    
    
    longestrun(a)
    
    0 讨论(0)
  • 2020-12-03 13:14
    def getSublists(L,n):
        outL=[]
        for i in range(0,len(L)-n+1):
            outL.append(L[i:i+n])
        return outL
    
    
    def longestRun(L):
        for n in range(len(L), 0, -1):
            temp=getSublists(L,n)
            for subL in temp:
                if subL==sorted(subL):
                    return len(subL)
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-12-03 13:27

    As an update to David Robinson's answer, it is now (Python 3.4) possible to return 0 on an empty sequence (instead of raising ValueError):

    import itertools
    max((sum(1 for _ in l) for n, l in itertools.groupby(lst)), default=0)
    
    0 讨论(0)
  • 2020-12-03 13:29

    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))
    
    0 讨论(0)
  • 2020-12-03 13:39
    def longestrun(myList):
        size = 1
        max_size = 0
        for i in range(len(myList)-1):
            if myList[i+1] = myList[i]:
                size += 1
            else: 
                size = 1
            if max_size<size:
                max_size = size
        return size 
    

    Remove the .split() from myList in main() and you're good to go with this.

    0 讨论(0)
提交回复
热议问题