Reputation: 2089
Consider the series:
s = [1, -1, 1, 1, 1, -1]
What is the most time-efficient way to count the number of times values in such series change? In this example, the answer is 3 (from 1 to -1, back to 1, and again to -1)
Upvotes: 3
Views: 2884
Reputation: 1188
I will go with this, Correct me if wrong..! :)
# This will append 1 in list if change occurs
c = [1 for i,x in enumerate(s[:-1]) if x!= s[i+1] ]
# Printing the length of list which is ultimately the total no. of change
print(len(c))
Upvotes: 1
Reputation: 4263
An alternative solution using numpy
is
np.count_nonzero(np.diff(s))
A native Python solution is
sum(s[i - 1] != s[i] for i in range(1, len(s)))
Upvotes: 2