In [7]:
from math import sqrt
def vector_add(v, w):
'''adds corresponding elements of vectors'''
return [v_i + w_i for v_i,w_i in zip(v, w)]
def vector_subtract(v, w):
'''subtract corresponding elements of vectors'''
return [v_i - w_i for v_i,w_i in zip(v, w)]
def vector_sum(vectors):
'''sum all corresponding elements'''
result = vectors[0]
for vector in vectors[1:]:
result = vector_add(result, vector)
return result
def vector_sum_fast(vectors):
'''sum all corresponding elements'''
return reduce(vector_add, vectors)
def scalar_multiply(c, vector):
'''c is the scalar'''
return [c * v_i for v_i in vector]
def vector_mean(vectors):
'''The ith element of the result is the mean of the ith element
of all the input vectors.'''
n = len(vectors)
return scalar_multiply(1/n, vector_sum(vectors))
def dot(v, w):
'''the sum of the product of the matching elements
of the input vectors'''
return sum(v_i * w_i for v_i,w_i in zip(v, w))
def sum_of_squares(v):
'''add the square of each element'''
return dot(v, v)
def magnitude(v):
'''Find the length of a vector in cartesian space'''
return sqrt(sum_of_squares(v))
def distance(v, w):
'''Find the distance between two vectors'''
return magnitude(vector_subtract(v, w))
a = [0, 5, 5]
b = [2, 5, 7]
distance(a, b)
Out[7]:
In [ ]: