zip: Walking Two Lists Together
~8 mincode completion
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.
Examples
The worked example from the prompt
- Input
- dot_product([1, 2, 3], [4, 5, 6])
- Output
- 32
Multiplying by zeros contributes nothing
- Input
- dot_product([1, 2], [0, 0])
- Output
- 0
Negative values subtract from the total
- Input
- dot_product([2, 3], [1, -1])
- Output
- -1
Hints
Hint 1
Walk the input once and accumulate as you go.
Hint 2
A common slip here: added instead of multiplied.
Requirements
Return the sum of a[0]b[0] + a[1]b[1] + ...
Constraints
Standard library only, no imports required
Time limit: 200 ms, Memory: 64 MB
Where this shows up
~8 min
••••••
3 employers weight this skill
2 frontier labs, 1 AI product company. Top match scores 80.
Python
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
pass