Python - counting sign changes

You can use itertools.groupby to count the groups of positive and non-positive numbers:

>>> x = [-3,2,7,-4,1,-1,1,6,-1,0,-2,1] 

>>> import itertools
>>> len(list(itertools.groupby(x, lambda x: x > 0)))

Result:

8

In your question you state that you want:

  • to count the changes, not the groups
  • to count an extra change if the first element is not positive.

You can do this either by testing the first element directly and adjusting the result:

>>> len(list(itertools.groupby(x, lambda x: x > 0))) - (x[0] > 0)

or by prepending a positive number to the input before doing the grouping then subtracting 1 from the result:

>>> len(list(itertools.groupby(itertools.chain([1], x), lambda x: x > 0))) - 1

Watch out if your input list could by empty - the former solution will raise an exception.


X = [-3,2,7,-4,1,-1,1,6,-1,0,-2,1]

last_sign = 1
sign_changes = 0

for x in X:
    if x == 0:
        sign = -1
    else:
        sign = x / abs(x)

    if sign == -last_sign:
        sign_changes = sign_changes + 1
        last_sign = sign

print sign_changes

Tags:

Python

List