[1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1]
It's just that I have a list like this and I need to find out what is the longest repetition of the number 1 in the sequence. In this case it would be 4. I know it's with cycles.
while i2<len(part_gan):
if part_gan[i2]!=part_gan[(i2+1)]:
mayor_racha+=1
i2+=1
return mayor_racha
I have this but, it gives me that list index out of range . (part_gan is the list above).
You have to take into account a very important thing, if in each iteration you index on
lista[i]
andlista[i + 1]
,i
it cannot becomelen(lista) - 1
(while i2 < len(part_gan)
).This is because when doing
lista[i + 1]
the last iteration you index withlista[len(lista)]
and that is an invalid index. Actually, since you only care about sequences of ones, you can simply iterate over an element and consider the sequence broken when an item is not 1.On the other hand, you need two variables, one to store the number of items in the longest sequence found so far, and another to count the items in the current sequence. When the current sequence of ones breaks you look to see if your current counter is greater than the maximum and if it is you update it, then you reset the counter of your current sequence and continue iterating.
We can use
max()
to simplify:Another option is to use
itertools.groupby
and get the maximum of the length of the groups of ones: