python-3.x - 在 Python 中不使用 np.dot 或循环来查找点积
问题描述
我需要编写一个函数:
- 接收 - 两个
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 - 当适合我的模型时,我得到 ValueError: Input 0 of layer sequence is incompatible with the layer
- javascript - 为什么我的 HTML 代码返回 [object HTMLFormElement]?
- javascript - 将预定义的对象插入空白的 Javascript 数组
- python-3.x - 如何通过在 Python 中的其他列上放置条件语句,用同一列中的现有字符串替换列中的 NaN 值
- html - 在我的 html 导航栏中。我的条贴在边距的左侧。我该如何补救?
- javascript - Jest - UnhandledPromiseRejection - 收到的承诺已解决而不是被拒绝
- ios - 转义闭包的运行时间
- python - 无法正常运行服务器/项目结构不正确?
- amazon-web-services - 我们如何借助 AWS Glue PySpark 中的 Cobol 布局/文案来读取 MainFrame 文件
- google-sheets - 如果同一行上两个值的减法相等,是否可以求和一个值?