Sign in to run and submit your work
Reading is open to everyone. Running code and saving drafts need an account so your work is yours and comes back on your next visit.
or
CODE WORKSPACE
A model multiplies a daily survival factor for each day of a month. To see how much one day contributes, the team wants the product of all the other days for each day. It is as if that day were removed. Some days have a factor of 0, because the service was down.
Write product_of_others(numbers). numbers is a list of integers. Return a list of the same length: the element at each position is the product of all the other numbers. Do not use division.
Function to write
product_of_others(numbers: list[int]) -> list[int]A list with, for each position, the product of all the other numbers.
How to approach it
Walk left to right and store the product of everything to the left of each position. Then walk right to left and multiply in the product of everything to the right.
Sample cases
+ 3 held back until you submit
four daily factors
The products of the others are 24, 12, 8 and 6.
Input
Argument 1
[
1,
2,
3,
4
]Returns
[
24,
12,
8,
6
]one zero
Only the position of the zero gets a non-zero answer (2 times 3 is 6). The others include the zero, so they are 0.
Input
Argument 1
[
2,
0,
3
]Returns
[
0,
6,
0
]two zeros
Every position has at least one zero among the others, so every answer is 0.
Input
Argument 1
[
0,
4,
0,
5
]Returns
[
0,
0,
0,
0
]empty list
No numbers gives an empty list.
Input
Argument 1
[] (empty list)
Returns
[] (empty list)
Constraints
i is the product of every number except the one at i.[1], because the product of nothing is 1.Worked example
Take [2, 0, 3]. Pass 1 stores the product of everything to the left of each position: [1, 2, 0]. Nothing is left of position 0, 2 is left of position 1, and 2 * 0 is left of position 2. Pass 2 walks from the right and multiplies in the product of everything to the right. Nothing is right of position 2, so it stays 0. For position 1, 3 is on the right, so 2 * 3 = 6. For position 0, 0 * 3 is on the right, so 1 * 0 = 0. The answer is [0, 6, 0].
The trap: dividing the total product by each number fails on the zero. In this list the total is 0, so every division would give a wrong answer.
What this tests
Prefix and suffix products, the idea behind 'Product of Array Except Self'. Two passes build the product of everything on the left and everything on the right. The same two-pass pattern gives running totals, 'everything except me' metrics, and leave-one-out checks without dividing.
product_of_others(numbers: list[int]) -> list[int]Submit for review to find out what your query gets right, what it gets wrong, and how it compares with the best working query for this exercise.
This scenario runs a full workspace — editor, canvas and results side by side. It needs a laptop or desktop to be usable. Open this page on a bigger screen to start building.