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?
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.
Numbers which follow each other in order, without gaps, from smallest to largest.
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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With