Python 3.x 在Python中不使用np.Dot或循环查找点积
我需要编写一个函数,该函数:Python 3.x 在Python中不使用np.Dot或循环查找点积,python-3.x,numpy,dot-product,Python 3.x,Numpy,Dot Product,我需要编写一个函数,该函数: 接收-两个numpy.array对象 返回-两个输入的浮点点积 numpy数组 不允许使用: numpy.dot() 任何类型的循环 有什么建议吗?再见 一种可能的解决方案是使用递归 import numpy as np def multiplier (first_vector, second_vector, size, index, total): if index < size: addendum = first_vector[i
numpy.array
对象numpy
数组numpy.dot()
import numpy as np
def multiplier (first_vector, second_vector, size, index, total):
if index < size:
addendum = first_vector[index]*second_vector[index]
total = total + addendum
index = index + 1
# ongoing job
if index < size:
multiplier(first_vector, second_vector, size, index, total)
# job done
else:
print("dot product = " + str(total))
def main():
a = np.array([1.5, 2, 3.7])
b = np.array([3, 4.3, 5])
print(a, b)
i = 0
total_sum = 0
# check needed if the arrays are not hardcoded
if a.size == b.size:
multiplier(a, b, a.size, i, total_sum)
else:
print("impossible dot product for arrays with different size")
if __name__== "__main__":
main()
将numpy导入为np
def乘数(第一个_向量、第二个_向量、大小、索引、总数):
如果索引<大小:
附录=第一个向量[索引]*第二个向量[索引]
总计=总计+附录
索引=索引+1
#正在进行的工作
如果索引<大小:
乘数(第一个向量、第二个向量、大小、索引、总数)
#工作完成
其他:
打印(“点产品=”+str(总计))
def main():
a=np.数组([1.5,2,3.7])
b=np.数组([3,4.3,5])
印刷品(a、b)
i=0
总和=0
#如果阵列未硬编码,则需要检查
如果a.size==b.size:
乘数(a、b、a、大小、i、总和)
其他:
打印(“不同大小阵列的不可能点积”)
如果名称=“\uuuuu main\uuuuuuuu”:
main()
可能被认为是作弊,但是numpy
使用的Python 3.5计算点积,而不实际调用np.dot
:
>>> arr1 = np.array([1,2,3])
>>> arr2 = np.array([3,4,5])
>>> arr1 @ arr2
26
问题解决了 这似乎是一个家庭作业问题。为什么不分享一些到目前为止你写的代码呢?问题是要求您在不使用循环和np.dot的情况下实现点积。看看一些numpy函数,看看是否有一种方法可以构造出与点积等价的东西。首先,你应该阅读并理解点积对两个向量的作用。它可能比你想象的要简单。你考虑过reduce()吗?@awiebe:没有必要(使用它会阻止你从numpy
中获益)。点积只是元素相乘,然后求和,它们被明确允许使用np.sum
,而且乘法很简单。有人刚刚帮你做了家庭作业-