I have to write a function that has two arguments(two lists of numbers, and returns its inner product), without using list comprehension, any ideas?

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?

3

2 Answers

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
1

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like