Have a go at it. The editor and the docs panel are open, and your code is saved as you type. Running it needs a free account — you’ll come back to exactly what you wrote.
zip: Walking Two Lists Together
zip pairs up two (or more) collections and lets you loop over both at once:
names = ["ada", "grace"]
ages = [36, 45]
for name, age in zip(names, ages):
print(name, age)
# ada 36
# grace 45If the lists are different lengths, zip stops at the shorter one. That is occasionally what you want and is very often a silent bug, so check your lengths when it matters.
This pattern shows up everywhere in machine learning: predictions and true labels are two parallel lists, and almost every metric is a loop over their pairs.
Your task:
Write dot_product(a, b) that multiplies the two lists element by element and returns the total.
For [1, 2, 3] and [4, 5, 6] that is 1*4 + 2*5 + 3*6, which is 32.
You will meet this operation again as the core of every linear model.
Example Tests
The worked example from the prompt
Input: {"a":[1,2,3],"b":[4,5,6]}
Expected: 32
Multiplying by zeros contributes nothing
Input: {"a":[1,2],"b":[0,0]}
Expected: 0
Negative values subtract from the total
Input: {"a":[2,3],"b":[1,-1]}
Expected: -1
def dot_product(a, b):
"""
Multiply two lists element by element and add up the results.
Args:
a, b: lists of numbers of the same length
Returns:
The sum of a[0]*b[0] + a[1]*b[1] + ...
"""
# YOUR CODE HERE
passRun your code to see results
⌘↵ runs against the visible tests