Python code for counting number of zero crossings in an array

前端 未结 6 1456
春和景丽
春和景丽 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:27

    I think a loop is a straight forward way to go:

    a = [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]
    
    def change_sign(v1, v2):
        return v1 * v2 < 0
    
    s = 0
    for ind, _ in enumerate(a):
        if ind+1 < len(a):
            if change_sign(a[ind], a[ind+1]):
                s += 1
    print s  # prints 8
    

    You could use a generator expression but it gets ugly:

    z_cross = sum(1 for ind, val in enumerate(a) if (ind+1 < len(a)) 
                  if change_sign(a[ind], a[ind+1]))
    print z_cross  # prints 8
    

    EDIT:

    @Alik pointed out that for huge lists the best option in space and time (at least out of the solutions we have considered) is not to call change_sign in the generator expression but to simply do:

    z_cross = sum(1 for i, _ in enumerate(a) if (i+1 < len(a)) if a[i]*a[i+1]<0)
    

提交回复
热议问题