Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find number of consecutive elements that are the same before they change

Tags:

python

list

So for example if I have the lists

a = [1,1,1,2,2]
b = [1,1,2,2,2]
c = [2,1,1,1,1]

I would want to get the longest streak of the first element in the list, so for example a would give 3, b would give 2 and c would give 1. I know I could create a while loop and count the streak that way, but I was wondering if there's a more elegant way to do this?

like image 973
user5368737 Avatar asked Jun 11 '16 17:06

user5368737


People also ask

How do you find consecutive numbers?

If we denote the 1st number as n, then the consecutive numbers in the series will be n, n+1, n+2, n+3, n+4, and so on. For any two consecutive odd numbers, the difference is 2. For example, 3 and 5 are two consecutive odd numbers, their difference = 5 - 3 = 2. For any two consecutive even numbers, the difference is 2.

What are consecutive elements?

Numbers which follow each other in order, without gaps, from smallest to largest.

How do you find consecutive numbers in Java?

Method 1 (Use Sorting) 1) Sort all the elements. 2) Do a linear scan of the sorted array. If the difference between the current element and the next element is anything other than 1, then return false. If all differences are 1, then return true.


1 Answers

you could do something like this:

numStreak = ([a[0] == n for n in a]+[False]).index(False)

(this also makes sure that if all elements are like the first element, index does return the correct value)

UPDATE: a more efficient (but less elegant?) version

from itertools import takewhile
len([1 for _ in takewhile(lambda x:x==a[0], a)])

or a bit better (UPDATE 2) @vaultah's suggestion:

sum(1 for _ in takewhile(lambda x:x==a[0], a))
like image 132
DomTomCat Avatar answered Sep 20 '22 16:09

DomTomCat