Home > Back-end >  Extending code to compute maximum dot product for arbitrary number of vectors
Extending code to compute maximum dot product for arbitrary number of vectors

Time:03-08

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

CodePudding user response:

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:

from itertools import combinations
def max_dot_p(vectors):
    return max(dot_p(x, y) for x, y in combinations(vectors, k=2)) 
  • Related