python_morsels/add/add.py

29 lines
1.1 KiB
Python
Raw Permalink Normal View History

def add_v1(*matrices):
m_sizes = [len(matrix) for matrix in matrices]
v_sizes = [len(vectors) for matrix in matrices for vectors in matrix]
same_values = lambda l: all(e == l[0] for e in l[1:])
if not same_values(m_sizes) or not same_values(v_sizes):
raise ValueError("Given matrices are not the same size.")
return [[sum(elt) for elt in zip(*vectors)] for vectors in zip(*matrices)]
def add_v2(*matrices):
2020-11-30 23:58:29 +01:00
get_shape = lambda matrix: [len(vector) for vector in matrix]
shape = get_shape(matrices[0])
if any(get_shape(matrix) != shape for matrix in matrices):
raise ValueError("Given matrices are not the same size.")
return [[sum(elt) for elt in zip(*vectors)] for vectors in zip(*matrices)]
def add_v3(*matrices):
def get_shape(matrix):
return [len(vector) for vector in matrix]
shape = get_shape(matrices[0])
if any(get_shape(matrix) != shape for matrix in matrices):
raise ValueError("Given matrices are not the same size.")
return [[sum(elt) for elt in zip(*vectors)] for vectors in zip(*matrices)]
add = add_v3