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.
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.
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)]))
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))