DDC-5: A dot production function
A data challenge a day helps you master machine learning
About these daily data challenges
Each post is an exercise that helps you learn about data in Python.
Try to solve the exercise before checking my solution at the bottom of the post 🤓
You can share your solution or visualization in the comments!
Today’s challenge
Write a Python function that calculates the dot product. Don’t use np.dot
; instead, implement the calculation directly:
Your Python function should take two inputs, both numpy arrays. Raise an exception (that is, have the function give an error) if either input is not a numpy array. Also give an error if the two variables have different lengths.
Check your function’s accuracy against np.dot as in the screenshot below. Also confirm that the function produces errors if the vectors have unequal lengths or are lists instead of numpy arrays.
.
.
.
.
Scroll down for the solution…
.
.
.
.
.
.
.
.
keep scrolling!
import numpy as np
def dotproduct(a,b):
# check that both vectors are numpy arrays
if not (isinstance(a,np.ndarray) and isinstance(b,np.ndarray)):
raise Exception('Must be numpy array')
# check that they have the same length
if not len(a)==len(b):
raise Exception('Must be the same length')
# return the dot product
return sum(a*b)