Python code for counting number of zero crossings in an array

前端 未结 6 1459
春和景丽
春和景丽 2021-02-08 01:44

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

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-08 02:22

    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.

提交回复
热议问题