-3

how do I find out the maximum amount of 1s (or any element I would like) next to each other in a list?

l = [2, 1, 2, 1, 1, 1, 1, 2, 2, 2, 1, 2, 7, 1, 1, 1]

In this case I would need a function that will return a 4.

Thank you.

Marcel Braasch
  • 1,083
  • 1
  • 10
  • 19
  • One possible solution is to use `itertools.groupby`, and then find the group with the highest count of 1s. – cs95 Dec 09 '17 at 23:44
  • Someone already provided a good answer, but I wonder what you have already tried. –  Dec 09 '17 at 23:51

2 Answers2

1

The groupby() function can be used for this:

import itertools

l = [2, 1, 2, 1, 1, 1, 1, 2, 2, 2, 1, 2, 7, 1, 1, 1]
print(max([len(list(g))*k for k, g in itertools.groupby(l, lambda x: x == 1)]))
VMatić
  • 996
  • 2
  • 10
  • 18
  • What happens if there are 10 adjacent `7`s? You need to filter the groups before `max`ing. –  Dec 09 '17 at 23:56
0

Manually:

def makeMyHomework(li):
'''reads a list of int's and looks for the logest run of one int'''
    curVal = None
    curCount = 0
    maxVal = None
    maxCount = -1
    for n in l:
        if curVal == None:
            curVal = n
        if curVal == n:
            curCount +=1
        if curVal != n:
            if curCount > maxCount: # check if current run > max so far
                maxVal = curVal      # store new max value
                maxCount = curCount  # store new max count
            curVal = n     # init the act ones
            curCount = 1   #  -"-

       # print (n, ":", curVal, curCount, maxVal,maxCount)

    # edge case - the max list is the last run            
    if curCount > maxCount:      
        maxVal = curVal
        maxCount = curCount

    return (maxVal, maxCount) # tuple of (value, number of occurences)

l = [2, 1, 2, 1, 1, 1, 1, 2, 2, 2, 1, 2, 7, 1, 1, 1,2,2,2,2,2]

print(makeMyHomework(l))
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69