I am looking to count the number of times the values in an array change in polarity (EDIT: Number of times the values in an array cross zero).
Suppose I have an array:<
Seems like, you want to group numbers by their sign. This could be done using built-in method groupby
:
In [2]: l = [80.6, 120.8, -115.6, -76.1, 131.3, 105.1, 138.4, -81.3, -95.3, 89.2, -154.1, 121.4, -85.1, 96.8, 68.2]
In [3]: from itertools import groupby
In [5]: list(groupby(l, lambda x: x < 0))
Out[5]:
[(False, ),
(True, ),
(False, ),
(True, ),
(False, ),
(True, ),
(False, ),
(True, ),
(False, )]
Then you should use function len
which returns the number of groups:
In [7]: len(list(groupby(l, lambda x: x < 0)))
Out[7]: 9
Obviously, there will be at least one group (for a non-empty list), but if you want to count the number of points, where a sequence changes its polarity, you could just subtract one group. Do not forget about the empty-list case.
You should also take care about zero elements: shouldn't they be extracted into another group? If so, you could just change the key
argument (lambda function) of groupby
function.