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
An order-level discount has to be pushed down to the line items so each item's revenue is reported net. Amounts are held in minor units — whole cents — because money is not a float. Splitting proportionally and rounding each share loses or gains a cent, and the finance reconciliation fails on the difference.
Write allocate(total_minor, weights). Return one whole amount per weight.
Function to write
allocate(total_minor: int, weights: list) -> list[int]One whole minor-unit amount per weight, summing to exactly the total.
How to approach it
Take the floor of each exact share, then hand out the leftover units by largest fraction.
Sample cases
+ 2 held back until you submit
a bill split three ways
One hundred units into three equal shares, where every share has the same leftover fraction.
Input
Argument 1
10000Argument 2
[
1,
1,
1
]Returns
[
3334,
3333,
3333
]a proportional discount
An odd total against uneven weights, so the remainder has to go somewhere specific.
Input
Argument 1
999Argument 2
[
50,
30,
20
]Returns
[
499,
300,
200
]nothing to split
A total of zero allocates zero to everybody rather than raising.
Input
Argument 1
0Argument 2
[
1,
2,
3
]Returns
[
0,
0,
0
]no weights at all
Nothing to allocate to, so the answer is an empty list and the total is simply unallocated.
Input
Argument 1
500Argument 2
[] (empty list)
Returns
[] (empty list)
Constraints
total_minor. That is the whole requirement; proportionality is the second one.Worked example
Splitting 10000 minor units three ways gives 3333.33 each. Rounding each share gives 3333 three times, which is 9999 — a cent short, and the invoice no longer adds up. The largest-remainder method takes the three floors of 3333, notices one unit is unallocated, and gives it to the first share: 3334, 3333, 3333. The rule about zero weights is the one that bites in production. A line item with no value has a fractional part of exactly zero, which ties with every other share that came out whole — and a naive 'give the remainder to whoever is next' hands a cent of discount to a line that was never discounted. Finance notices.
What this tests
That money is integer arithmetic with a distribution rule, not floating-point division with rounding. The largest-remainder method is the standard answer and the reason it exists is exactly the failure in the naive version.
allocate(total_minor: int, weights: list) -> 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.