New add function using def instead of lambda; all versions in one file.
This commit is contained in:
parent
14152b9a30
commit
9c5f9d0c86
24
add/add.py
24
add/add.py
|
|
@ -1,6 +1,28 @@
|
||||||
def add(*matrices):
|
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):
|
||||||
get_shape = lambda matrix: [len(vector) for vector in matrix]
|
get_shape = lambda matrix: [len(vector) for vector in matrix]
|
||||||
shape = get_shape(matrices[0])
|
shape = get_shape(matrices[0])
|
||||||
if any(get_shape(matrix) != shape for matrix in matrices):
|
if any(get_shape(matrix) != shape for matrix in matrices):
|
||||||
raise ValueError("Given matrices are not the same size.")
|
raise ValueError("Given matrices are not the same size.")
|
||||||
return [[sum(elt) for elt in zip(*vectors)] for vectors in zip(*matrices)]
|
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
|
||||||
|
|
|
||||||
|
|
@ -1,7 +0,0 @@
|
||||||
def add(*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)]
|
|
||||||
Loading…
Reference in a new issue