Dot product (Python)

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

[edit] Iteration

<<vector_dot_product_iteration.py>>=
def dot(vector1, vector2):
    result = 0
    for (v1, v2) in zip(vector1, vector2):
        result += v1 * v2
    return result

[edit] Recursion

<<vector_dot_product_recursion.py>>=
def dot(vector1, vector2):
    if vector1 and vector2:
        return vector1[0] * vector2[0]\
            + dot(vector[1:], vector2[1:])
    else:
        return 0

[edit] Functional

<<vector_dot_product_functional.py>>=
def dot(vector1, vector2):
    return sum(map(lambda a, b: a * b, vector1, vector2)))
Download code
hijacker
hijacker
hijacker
hijacker