Lists aren't vectors =/ We need to help them become such.
In [1]:
def vector_add(v, w):
'''adds two vectors element by element'''
return [v_i + w_i
for v_i, w_i in zip(v,w)]
In [2]:
a = [1,2,3]
b = [5,6,7]
In [3]:
vector_add(a,b)
Out[3]:
In [4]:
def vector_subtract(v, w):
'''subtracts element by element'''
return [v_i - w_i
for v_i, w_i in zip(v,w)]
In [5]:
vector_subtract(a,b)
Out[5]:
In [6]:
# we can sum an arbitrary number of vectors with reduce
def vector_sum(vectors):
return reduce(vector_add, vectors) # combine vectors with rule vector_add
In [7]:
vector_sum([a,b,a,b])
Out[7]:
In [8]:
def scalar_multiply(c, v):
'''Takes scalar c and multiplies it by vector v'''
return [c * v_i for v_i in v]
In [9]:
scalar_multiply(4,a)
Out[9]:
In [10]:
from __future__ import division
def vector_mean(vectors):
'''elementwise mean of a collection of vectors'''
n = len(vectors)
return scalar_multiply(1/n, vector_sum(vectors))
In [11]:
vector_mean([a,b])
Out[11]:
In [12]:
def dot(v, w):
'''We want the sum of the element wise products'''
return sum(v_i * w_i
for v_i,w_i in zip(v,w))
In [13]:
dot(a,b)
Out[13]:
In [14]:
def sum_of_squares(v):
'''Simply the self dot product'''
return dot(v,v)
In [15]:
sum_of_squares(a)
Out[15]:
In [16]:
import math
def magnitude(v):
return math.sqrt(sum_of_squares(v))
In [17]:
magnitude(a)
Out[17]:
In [18]:
# This is the sum of squares of the difference vector
def squared_distance(v, w):
return sum_of_squares(vector_subtract(v, w))
# Which allows us to calc the distance
def distance(v,w):
return math.sqrt(squared_distance(v, w))
# More directly, the magnitude of the difference vector
def distance(v,w):
return magnitude(vector_subtract(v, w))
In [19]:
distance(a,b)
Out[19]:
In [20]:
# Shape
def shape(A):
num_rows = len(A)
num_cols = len(A[0]) if A else 0
return num_rows, num_cols
In [21]:
A = [[1,2,3],
[4,5,6]]
B = [[2,4],
[6,8],
[10,12]]
In [22]:
shape(A)
Out[22]:
In [23]:
shape(B)
Out[23]:
In [24]:
def get_row(A, i):
return A[i]
def get_column(A, j):
return [A_i[j]
for A_i in A]
In [30]:
def make_matrix(num_rows, num_cols, make_fn):
return [[make_fn(i, j)
for j in xrange(num_cols)]
for i in xrange(num_rows)]
def is_diagonal(i, j):
'''1s on diag 0 otherwise'''
return 1 if i == j else 0
In [31]:
make_matrix(4,4, is_diagonal)
Out[31]:
In [ ]: