Saeed
Saeed

Reputation: 2089

Count the number of times values change in a series

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

Answers (3)

0xPrateek
0xPrateek

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

enter image description here

Upvotes: 1

GZ0
GZ0

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

BENY
BENY

Reputation: 323226

I will using numpy

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

Upvotes: 5

Related Questions