50 XP

52. Product of the others

Intermediate lists

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

Inputnumbers = [2, 3, 4, 5]
Output[60, 40, 30, 24]
Explanation60 = 3 * 4 * 5, 40 = 2 * 4 * 5, and so on.

Example 2

Inputnumbers = [2, 0, 5]
Output[0, 10, 0]
ExplanationOnly the 0's own answer skips the 0.

Example 3

Inputnumbers = [7]
Output[1]
ExplanationNo other items: the empty product is 1.

Constraints

  • numbers has 0 to 30 whole numbers, each from -10 to 10.

Submit also runs 8 more tests you can't see.

Practises Lists (lesson 9).

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