扩展代码以计算任意数量向量的最大点积
如果列表中的向量超过 3 个,如何修改代码才能使 max_dot_p
正常工作? (dot_p
是点积)
这是我尝试过的:
def dot_p(vector1, vector2):
total = 0
for x, y in zip(vector1, vector2):
total += x * y
return total
def max_dot_p(vectors):
product = []
for i in range(len(vectors)):
for j in range(len(vectors)):
dot_p = dot_product(vectors[i] , vectors[j])
product.append(dot_p)
continue
max_product = max(product)
return max_product
if __name__ == "__main__":
vectors = [[5, 6], [13, 1], [3, 1]
print(max_dot_p(vectors))
尽管它确实运行了,但它没有给我预期的答案
How can I modify my code so that the max_dot_p
works if there are more than 3 vectors in the list? (dot_p
is dot product)
Here is what I have tried:
def dot_p(vector1, vector2):
total = 0
for x, y in zip(vector1, vector2):
total += x * y
return total
def max_dot_p(vectors):
product = []
for i in range(len(vectors)):
for j in range(len(vectors)):
dot_p = dot_product(vectors[i] , vectors[j])
product.append(dot_p)
continue
max_product = max(product)
return max_product
if __name__ == "__main__":
vectors = [[5, 6], [13, 1], [3, 1]
print(max_dot_p(vectors))
It does not give me the expected answer, although it does run
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 itertools.combinations 选择两个向量传递到点积函数中,然后在点积函数的所有调用中取最大值:
You can use
itertools.combinations
to select two vectors to pass into your dot product function, and then take the maximum value across all invocations to your dot product function: