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:<
Based on Scott's answer
The generator expression proposed by Scott uses enumerate
which returns tuples containing index and list item. List item are not used in the expression at all and discarded later. So better solution in terms of time would be
sum(1 for i in range(1, len(a)) if a[i-1]*a[i]<0)
If your list a
is really huge, range may throw an exception. You can replace it with itertools.islice
and itertools.count
.
In Python version 2.x, use xrange instead of Python 3's range
.
In Python 3, xrange
is no longer available.