Home > Mobile >  I have to write a function that has two arguments(two lists of numbers, and returns its inner produc
I have to write a function that has two arguments(two lists of numbers, and returns its inner produc

Time:07-23

def inner_product(vec1,vec2):
    if len(vec1)==len(vec2) and len(vec1)!=0:
        return sum([vec1[n]*vec2[n] for n in range(len(vec1))])
    else:
        return 0

Is the code that I built contain using list comprehension? if yes what can I do instead of this?

CodePudding user response:

Yes.
Without list comprehension, it would be something like below.

def inner_product(vec1,vec2):
    if len(vec1)==len(vec2) and len(vec1)!=0:
        temp=[]
        for n in range(len(vec1)):
            temp.append(vec1[n]*vec2[n])
        return sum(temp)
    else:
        return 0

CodePudding user response:

A basic for-loop approach.

def inner_product(vec1, vec2):
    result = 0
    if len(vec1) == len(vec2) and len(vec1) != 0:
        for i in range(len(vec1)):
            result  = vec1[i] * vec2[i]
    return result


print(inner_product([1, 2, 3], [4, 5, 6]))
#32
print(inner_product([1, 2, 3], [4, 5, 6, 5555]))
#0

Notice that your current implementation returns 0 if the vectors have different length... but careful that a inner product return zero if and only if the two vectors are orthogonal to each other (assumed both vectors non zero)... and this geometrical result will fail. Raising an exception would be a good choice to fix it: raise Exception("Error, vectors non comparable")

  • Related