我需要编写一个函数:
- 接收 - 两个
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()
可能被认为是作弊,但 Python 3.5 添加了一个矩阵乘法运算符,numpy
使用它来计算点积而不实际调用np.dot
:
>>> arr1 = np.array([1,2,3])
>>> arr2 = np.array([3,4,5])
>>> arr1 @ arr2
26
问题解决了!