python - 在 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])))
解决方案
您可以通过遍历数组来实现您想要的,如下所示:
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"
。
推荐阅读
- java - 在 Canvas Android 上拖动一个矩形
- c# - 将 rel="nofollow" 自动添加到 ASP.NET 中的所有出站链接
- winforms - 使用 WiX 引导程序安装 winforms 应用程序的先决条件
- python - 将数据帧总数附加到新数据帧
- python - 在二分法中得到错误的输出
- java - 从动态 Firebase 数据库中提取变量
- javascript - 编写一个名为 cube 的函数,它接受一个参数 n
- c# - 如何更改多个 Active Directory 用户密码?
- javascript - Angular Datatables 和 Angular Material Table 组合
- reactjs - 继续获取 React this.setState is not a function 尽管已绑定