52. Product of the others
Write a function products(numbers) that takes a list of whole numbers and returns a new list of the same length,
whose item i is the product of every item of numbers except the one at index i.
- Don't divide. Multiplying everything and dividing by each item fails as soon as an item is 0.
- A product of no numbers at all is 1, so a list with one item gives
[1]. - An empty list gives an empty list
[].
Example 1
Input
numbers = [2, 3, 4, 5]Output
[60, 40, 30, 24]Explanation60 = 3 * 4 * 5, 40 = 2 * 4 * 5, and so on.
Example 2
Input
numbers = [2, 0, 5]Output
[0, 10, 0]ExplanationOnly the 0's own answer skips the 0.
Example 3
Input
numbers = [7]Output
[1]ExplanationNo other items: the empty product is 1.
Constraints
numbershas 0 to 30 whole numbers, each from -10 to 10.
Submit also runs 8 more tests you can't see.
Practises Lists (lesson 9).
- The answer for index
iis (the product of everything beforei) times (the product of everything afteri). - One loop from left to right can keep a running product of what came before: store it as
result[i], then multiply innumbers[i]. - A second loop from right to left does the same for what comes after, multiplying it into
result[i]. Start both running products at 1.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Was this challenge helpful?
Thanks!
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
Code
def products(numbers):
"""Multiply together all the items but one, for each.
numbers: list of int; may be empty
Returns: list of int, item i is the product of every
item except numbers[i]
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.