简体   繁体   English

我必须编写一个有两个参数的函数(两个数字列表,并返回其内积),而不使用列表理解,有什么想法吗?

[英]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?如果是的话,我能做些什么来代替这个?

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

A basic for -loop approach.一种基本的 for循环方法。

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.请注意,如果向量具有不同的长度,您当前的实现将返回0 ...但请注意,当且仅当两个向量相互正交(假设两个向量均非零)时,内积才返回零...以及此几何结果将失败。 Raising an exception would be a good choice to fix it: raise Exception("Error, vectors non comparable")引发异常是修复它的好选择: raise Exception("Error, vectors non comparable")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM