首页 > 解决方案 > 在 Python 中不使用 np.dot 或循环来查找点积

问题描述

我需要编写一个函数:

  1. 接收 - 两个numpy.array对象
  2. numpy返回 - 两个输入数组的浮点点积

不允许使用:

  1. numpy.dot()
  2. 任何类型的循环

有什么建议么?

标签: python-3.xnumpydot-product

解决方案


再见,

一个可能的解决方案利用递归

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()

推荐阅读