Count the number of times values change in a series

Viewed 1829

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)

3 Answers

I will using numpy

(np.diff(s)!=0).sum()
Out[497]: 3

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

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

enter image description here

Related