Adding vectors (Python)

From LiteratePrograms
Jump to: navigation, search
Other implementations: Haskell | Python

Vector addition


\overrightarrow{u} + \overrightarrow{v}
=
\begin{bmatrix} 
u_1 & u_2 & ... & u_n
\end{bmatrix}
+
\begin{bmatrix} 
v_1 & v_2 & ... & v_n
\end{bmatrix}
=
\begin{bmatrix} 
u_1 + v_1 & u_2 + v_2 & ... & u_n + v_n
\end{bmatrix}

Contents

[edit] Iteration

<<vector_addition_iterative.py>>=
def vadd(vector1, vector2):
    newVector = []
    for (v1, v2) in zip(vector1, vector2):
        newVector.append(v1 + v2)
    return newVector

[edit] Iteration - Inplace

<<vector_addition_iterative_inplace.py>>=
def vadd(vector1, vector2):
    for i, (v1, v2) in enumerate(zip(vector1, vector2)):
        vector1[i] = v1 + v2
    return vector1

[edit] Functional

<<vector_addition_functional.py>>=
def vadd(vector1, vector2):
    return map(lambda x, y: x + y, vector1, vector2)

[edit] Recursion

<<vector_addition_recursive.py>>=
def vadd(vector1, vector2):
    if vector1 and vector2:
        return [vector1[0] + vector2[0]] + vadd(vector1[1:], vector2[1:])
    else:
        return []

[edit] List Comprehension

<<vector_addition_list_comprehension.py>>=
def vadd(vector1, vector2):
    return [ v1 + v2 for (v1, v2) in zip(vector1, vector2) ]
Download code
hijacker
hijacker
hijacker
hijacker