Write a function that takes 2 lists and finds the Euclidean distance between them. Note you may not use any third-party modules. Use a comprehension to solve the problem and use an assert statement to make sure the lists are of equal length. (这是我们学校 career dept提供的模拟笔试的题
同学你好,这个问题直接按照欧式距离的定义来弄就好了。
import math
def EuclideanDistance(vec1, vec2):
assert (len(vec1) == len(vec2)), 'The first vector has length {} while the second vector has length {} which is not equal.'.format(len(vec1), len(vec2))
return math.sqrt(sum([ (v1 - v2) * (v1 - v2) for v1, v2 in zip(vec1, vec2)]))
print(EuclideanDistance([], []))
print(EuclideanDistance([1, 4], [3, 4]))
print(EuclideanDistance([1], []))