首页 > 解决方案 > 在 Python 中计算数组的元素

问题描述

我一直在寻找练习的答案。这个练习给了我们一个数字在 -1 和 1 之间的数组。我们被要求计算信号数组改变符号的次数。例如:你有这个数组:[0.7,0.5,0.6,-0.1,0.9,0.6,0.4,-0.2,-0.3,0.2,0.3,-0.3,-0.9,-0.7,0.1,0.2] 它改变符号7 次 这是我编写的代码,它应该得到它改变标志的次数的“计数”。由于某种原因,它不起作用,最后的计数等于 0,应该是 7。你能帮帮我吗?非常感谢你。

- 编码 -

import numpy as np

def zeroCrossing(signal):

    j=0
    ls=len(signal)
    print(ls)
    count=0
    x=0
    y=0
    for j in range(0,ls):
        if signal[j]>0 and x==1:
            j=j+1
            y=0
        elif signal[j]>0 and x==0:
            count==count+1
            x=1
            j=j+1
        elif signal[j]<0 and y==1:
            j=j+1
            x=0
        elif signal[j]<0 and y==0:
            count==count+1
            y=1
            j=j+1
    
    return count

print(zeroCrossing(np.array([0.7,0.5,0.6,-0.1,0.9,0.6,0.4,-0.2,-0.3,0.2,0.3,-0.3,-0.9,-0.7,0.1,0.2])))

标签: pythonarraysnumpycountreturn-value

解决方案


您可以通过遍历数组来实现您想要的,如下所示:

sign_changes = 0
last_number = None
for n in my_array:
    if n < 0: # checks if n is negative
        if last_number != "negative": # checks if the last number was not negative
            sign_changes += 1
        last_number = "negative"
    else: # takes n as positive (including 0)
        if last_number != "positive": # checks if the last number was not positive
            sign_changes += 1
        last_number = "positive"

编辑:

正如 OP 所期望的那样,此代码将在 OP 给出的示例数组中计数 7,它将第一个数字计为“符号更改”。为了避免这种情况(而是计算 6 个符号更改),可以对代码进行一些小的调整。最简单的是将last_number != "positive"last_number != "negative"条件分别更改为last_number == "negative"last_number == "positive"


推荐阅读