Three US offices send their gift requests to a workplace coordinator. The approved pool contains 103 identical gifts, but separately rounded office shares add up to 104. To make the sheet balance, the coordinator removes one from the last row. The stock now reconciles, yet nobody can explain why that office lost a unit.

Download the allocation workbook (English)
The useful correction is to replace the unexplained adjustment with a rule agreed before the calculation. Keep each office's whole-number share, then assign the remaining units by the size of the fractional remainders. If remainders tie, use an explicit, stable office-ID rule. The final recommendation must contain exactly 103 whole gifts, without depending on who submitted a row first.
This guide uses exact integer arithmetic to allocate an already approved total among offices with agreed integer weights. It includes the complete local Python model and examples you can run. It does not decide eligibility, establish available-to-promise inventory, reserve gifts, divide shipping cases, or arrange delivery.
That boundary matters. A mathematically consistent allocation can still begin with an outdated headcount or an unapproved stock total. Freeze those inputs first. Then the calculation can answer a narrow, useful question: how should this fixed count of identical units be divided under this documented proportional rule?
Agree what the total and weights mean
The total is a count of individual identical gifts. If the approved pool is 103 mugs, enter 103 units, not a number of cartons or a dollar value. Different products, sizes, or eligibility groups require a separately agreed allocation scope; this model does not treat unlike items as interchangeable.
Weights express the same basis for every office. They might be eligible headcounts from one approved snapshot. BOS=50, DEN=30, and SEA=20 then mean 100 eligible people counted using the same rule and cutoff. Do not combine one office's full workforce with another office's registered participants and call the result proportional headcount allocation.
Before running the model, decide who belongs in the snapshot and who approves it. Resolve remote workers, recent transfers, duplicate records, and people attached to multiple offices in that upstream process. The function consumes the resulting counts; it neither detects those personnel issues nor makes the policy decision for you.
If there are special-purpose reserves, minimum guarantees, or maximum-per-person limits, resolve them before supplying the inputs or select a different documented rule. This model can allocate more gifts than people when the total exceeds the sum of weights. A proportional result is not automatically a one-gift-per-person program.
Record the approved total, snapshot date, office list, weight meaning, tie rule, and approver together. That small input record explains the recommendation more reliably than an isolated screenshot of final numbers.
Use the full input contract without silent repairs
The total must be a nonnegative Python integer. Every weight must also be a nonnegative Python integer. The model deliberately rejects booleans, fractional values, text counts, and negatives. In Python, a boolean can behave like an integer in some operations; the explicit type check prevents True from silently becoming one gift.
Each office ID must be a unique, nonempty ASCII string. The function does not trim spaces, change case, or normalize IDs. BOS and bos are distinct accepted IDs. A string containing spaces is not empty, so an upstream office register should determine whether that identifier is meaningful before it reaches the model. Do not invent an additional normalization step and assume it leaves the accepted contract unchanged.
Tied remainders are ordered by case-sensitive ascending ASCII office ID, independent of input row order. Uppercase and lowercase can therefore sort differently. Use approved stable IDs, rather than changing names or IDs to improve an office's position after seeing a tie.
Zero-weight offices remain in the output with zero gifts. An empty office list is valid only when total is zero. An all-zero weight set returns zeros when total is zero and is rejected when the total is positive. Those branches avoid dividing by zero while making the absence of a positive allocation basis explicit.
Invalid data needs an accountable correction upstream. Converting the text count '2' to 2, dropping a duplicate, or rounding a fractional weight may be reasonable in a separate data-cleaning decision, but this function does none of them silently. Correct the input record, obtain the needed approval, and run a new version.
How largest remainders conserve whole gifts
The US Census Bureau's Methods of Apportionment describes the historical Hamilton/Vinton approach: keep the whole part of each quota, then distribute leftover units in descending fractional order. Here, that arithmetic is adapted to identical gifts. It is not an HR fairness endorsement or a claim about the current method for allocating House seats.
Let the denominator be the sum of all office weights. For each office, multiply total gifts by its weight to obtain an integer numerator. Divide that numerator by the denominator using integer division to obtain the base allocation. The remainder numerator is what is left after that division.
All offices share the same denominator. Comparing their integer remainder numerators therefore gives exactly the same order as comparing their fractional remainders. There is no need to convert quotas into rounded percentages or floating-point decimals.
Subtract the sum of the bases from the total. That gives the count of units still to assign. Rank offices by descending remainder numerator, breaking equal remainders by the agreed office ID, and add one to each of the first offices in that ranking until the remainder pool is exhausted.
For valid positive-weight input, each final allocation is either the floor or ceiling of its exact quota. Outputs are nonnegative integers, their sum equals the approved total, and zero weights stay zero. Those properties explain what the method guarantees. They do not establish whether the chosen eligibility basis or tie policy is appropriate for your organization.
Worked decision: allocate 103 gifts among Boston, Denver, and Seattle
Assume the approved total is 103 identical gifts and the agreed weights are BOS=50, DEN=30, and SEA=20. The denominator is 50 + 30 + 20 = 100. Assume there is no minimum guarantee, no separate reserve within this pool, and no additional per-person cap.
Boston's numerator is 103 × 50 = 5,150. Integer division by 100 gives a base of 51 gifts and a remainder numerator of 50. Denver's numerator is 3,090, giving base 30 and remainder 90. Seattle's numerator is 2,060, giving base 20 and remainder 60.
| Office ID | Weight | Numerator | Base gifts | Remainder numerator, denominator 100 | Remainder rank | Final gifts |
|---|---|---|---|---|---|---|
| BOS | 50 | 5150 | 51 | 50 | 3 | 51 |
| DEN | 30 | 3090 | 30 | 90 | 1 | 31 |
| SEA | 20 | 2060 | 20 | 60 | 2 | 21 |
The bases sum to 51 + 30 + 20 = 101 gifts. The remainder pool contains 103 − 101 = 2 gifts. Denver ranks first with 90, Seattle second with 60, and Boston third with 50. Award one additional gift to Denver and one to Seattle. The result is BOS51, DEN31, SEA21, totaling 103.
The coordinator can now explain why Denver and Seattle receive the two units beyond their bases. No row is adjusted simply because it appears last. Reviewers can reconstruct every value from the approved total and weights.
Accept the recommendation only after confirming the input snapshot, all three IDs, the common weight definition, and the final sum. If Seattle's weight turns out to include ineligible records, do not subtract a guessed number from Seattle's final allocation. Correct the weight, version the inputs, recompute all offices, and review the new result. An input change can alter the ranking beyond the affected row.
Worked decision: an exact tie for two gifts
Assume total is 2 and ATL, BOS, and CHI each have weight 1. The denominator is 3. Each numerator is 2 × 1 = 2, each base is 0, and each remainder numerator is 2. The base sum is zero, leaving two units to distribute.
Because the remainders are equal, compare office IDs in ascending case-sensitive ASCII order. ATL comes before BOS, which comes before CHI. The final result is ATL1, BOS1, CHI0. Submitting rows in the order CHI, ATL, BOS produces the same result.
This tie-break is deterministic; it does not express a judgment that Atlanta or Boston deserves more. Agree to it before reviewing the allocation. If the organization wants ties to rotate across recurring programs, it needs a separately specified and versioned rotation rule. Changing the IDs or reversing the order after a disappointing outcome would create a different model.
Notice that these weights represent three eligible units of demand, but only two gifts exist. If a minimum of one gift per office is mandatory, that requirement cannot be met with this total. The acceptance decision is then to revise the pool or the program requirements, rather than disguising the shortfall with rounding.
Review the tie record, confirm that the approved policy really permits a zero allocation, and check conservation: 1 + 1 + 0 = 2 gifts. If either the tie rule or the minimum requirement was not agreed, hold the recommendation for a policy decision. The code cannot settle an unresolved organizational commitment.
Run the complete local Python model
The function below implements the stated domain and tie contract. Supply rows as pairs of office ID and integer weight. It converts the iterable to a list, validates IDs and counts, handles the zero-denominator branch, and returns results ordered by office ID. It does not write inventory records or contact another service.
def allocate(total, rows):
if type(total) is not int or total < 0:
raise ValueError('total must be a nonnegative integer')
rows = list(rows)
seen = set()
for key, weight in rows:
if (type(key) is not str or not key or not key.isascii()
or key in seen):
raise ValueError('unique nonempty ASCII office IDs required')
if type(weight) is not int or weight < 0:
raise ValueError('weights must be nonnegative integers')
seen.add(key)
denominator = sum(w for _, w in rows)
if denominator == 0:
if total:
raise ValueError('positive total needs positive weight')
return {k: 0 for k, _ in sorted(rows)}
base = {k: total*w // denominator for k, w in rows}
remaining = total - sum(base.values())
rank = sorted(rows, key=lambda row:
(-(total*row[1] % denominator), row[0]))
for key, _ in rank[:remaining]:
base[key] += 1
return dict(sorted(base.items()))
The multiplication, integer division, and modulo operations preserve exact integer values. The negative remainder in the sorting key places larger remainders first; the ID is the secondary key. Sorting the returned dictionary makes its presentation stable too, but the allocation itself already ignores submitted row order.
This implementation intentionally uses Python integers rather than spreadsheet-style rounding. Do not replace its core arithmetic with ROUND, truncate large numerators to a display precision, or narrow the input domain to fit an unrelated export format. If another implementation is needed, verify that it preserves the same domain, zero behavior, and tie contract.
Three executable fixtures to try first
After defining the function, run these three assertions. They cover a complete proportional decision, a zero-weight office, and an exact tie. The expected results are outputs of the displayed model, rather than hand-adjusted targets.
assert allocate(103, [('BOS', 50), ('DEN', 30), ('SEA', 20)]) == {
'BOS': 51, 'DEN': 31, 'SEA': 21
}
assert allocate(1, [('A', 0), ('B', 4)]) == {'A': 0, 'B': 1}
assert allocate(2, [('CHI', 1), ('ATL', 1), ('BOS', 1)]) == {
'ATL': 1, 'BOS': 1, 'CHI': 0
}
For the second assertion, the denominator is 4. A's numerator and base are zero; B's numerator is 4 and its base is 1. Nothing remains to distribute. Including A in the result makes the zero explicit instead of silently removing an office from the record.
For the third assertion, the input deliberately starts with CHI. The result still awards ATL and BOS because the tie contract is based on IDs. Reorder the first fixture's rows as another check: its final shares should stay unchanged.
Assertions are a useful starting point for reproducing the calculation. Keep the input record and full boundary expectations alongside any version you adapt. If an assertion fails after a modification, investigate the changed arithmetic or contract before using the output for a real decision.
Check zeros, invalid inputs, and rounding boundaries
The table gives additional expected behavior. Counts in quotation marks are text, not integers. A rejection means the inputs require correction; it is not an instruction to replace the result with zeros or guess a conversion.
| Total | Rows or condition | Expected result | Reason to retain the case |
|---|---|---|---|
| 0 | A5, B0 | A0, B0 | Zero stock with a positive weight is valid |
| 0 | Empty list | {} | No offices requires zero total |
| 0 | A0, B0 | A0, B0 | All-zero weights are valid only with zero total |
| 1 | A0, B4 | A0, B1 | Zero weight remains zero |
| 10 | A1, B1 | A5, B5 | Exact equal division needs no remainder awards |
| 1 | A1, B1 | A1, B0 | Exact-half tie follows ID |
| 1 | A499, B501 | A0, B1 | B has the larger exact remainder |
| 1 | A500, B500 | A1, B0 | The middle boundary follows ID, not rounding preference |
| 1 | A501, B499 | A1, B0 | A has the larger exact remainder |
| 1 | A0, B0, or empty list | Reject | Positive total needs positive weight |
| −1 or 1.5 | A1 | Reject | Total must be a nonnegative integer |
| 1 | A weight −1 or text '2' | Reject | Weights must be nonnegative integers |
| 1 | Duplicate A IDs | Reject | No duplicate office identity |
| True | A1 | Reject | Boolean total is excluded |
| 1 | A weight True | Reject | Boolean weight is excluded |
| 1 | Empty, non-ASCII, or non-string ID | Reject | Office ID contract must hold |
The 499/501, 500/500, and 501/499 examples show why exact halves belong in the fixtures. The result at the tie comes from the ID rule. It does not use bankers' rounding or depend on a spreadsheet cell's displayed decimal places.
Review the recommendation before exporting it
For each valid run, retain office ID, weight, numerator, base, remainder numerator, rank, and final allocation. Include the common denominator once in the run record or clearly alongside the table. The final total should reconcile to the approved input total without a manual balancing line.
Use this acceptance checklist:
- Confirm the approved total and consistent weight snapshot.
- Confirm that office IDs match the approved register and are unique.
- Check that every output is a nonnegative integer.
- Check that outputs sum exactly to the input total.
- Check that zero weights receive zero.
- Check that each allocation is the floor or ceiling of its exact quota.
- Reorder the input rows and confirm the same result.
- Record the tie rule, model version, reviewer, and approval decision.
Presentation can be friendlier than code, but it must not alter the numbers. Keep numeric counts as whole units and make office IDs visible. If you export to another system, compare the exported totals and IDs with the reviewed recommendation. An export that changes case or removes leading spaces may change identity assumptions and deserves explicit handling.
Treat a changed total as a new allocation
Largest-remainder outcomes can change in unintuitive ways when the total changes. Do not assume that increasing the pool simply adds gifts to the previous result while leaving every earlier share intact. Recompute the entire allocation with the approved new total and review it as another version.
For a concrete additional calculation, assume weights A=5, B=3, and C=1. Their denominator is 9. With four gifts, numerators are 20, 12, and 4. Bases are 2, 1, and 0, leaving one gift; remainder numerators are 2, 3, and 4. C receives the remainder gift, producing A2, B1, C1.
Now increase the total to five gifts without changing weights. Numerators become 25, 15, and 5. Bases remain 2, 1, and 0, but two gifts remain. Remainder numerators are now 7, 6, and 5. A and B receive those gifts, producing A3, B2, C0. Both runs conserve their own totals and satisfy their exact quotas, yet C's share decreases when the pool grows.
This behavior is a property to consider when choosing the policy, rather than an arithmetic error to repair on C's row. If retaining every office's earlier allocation as the total grows is a mandatory program requirement, this model does not meet that requirement in general. Select an appropriate separately documented approach instead of advertising a guarantee the model cannot provide.
That is especially important when an earlier recommendation has already been approved. The local function does not know about units reserved, packed, distributed, or unavailable for another reason. Running it again does not add a reservation or reconcile an operational ledger.
If gifts have already moved, resolve the new approved allocation scope with the responsible team before calculating. Do not subtract prior output from a new output and automatically call the difference a shipping instruction. Negative differences or changed rankings need a reviewed operational decision outside this mathematical model.
Keep an approved version intact when a revised recommendation is prepared. Record which total and snapshot the new version supersedes, who requested the change, and whether an operational team has already acted on the earlier version. Comparing two records is clearer than overwriting the original cells and leaving reviewers unable to reconstruct the first decision. Approval of the arithmetic and authorization to move physical stock should each be visible in the appropriate record.
The original coordinator's 104-versus-103 problem now has a traceable resolution: one approved total, one snapshot, exact bases and remainder awards, and a documented tie rule. Any later change should preserve that same clarity instead of returning to unexplained edits.
Questions office coordinators often ask
Can weights be percentages? Use agreed nonnegative integer weights. If percentages are represented as integer weights on a common basis, record that basis. Do not pass fractional values or text and expect automatic conversion.
Does every office get at least one? No. A small total can leave some positive-weight offices at zero. Resolve minimum guarantees before adopting this model.
Can we sort by submission time? That would change the tie contract. This version uses ascending case-sensitive ASCII ID, independent of row order.
Does sum preservation prove the allocation is fair? It proves conservation under the chosen arithmetic. Eligibility, caps, reserves, and the tie policy still need organizational agreement.
Bring an approved distribution brief to Giftpack
Giftpack describes merchandise and gifting services. If relevant to your program, discuss the approved product, office allocations, recipient requirements, and distribution constraints, then confirm the actual service scope and availability.
Keep the reviewed allocation and its input version with that brief. Do not infer live stock visibility, reservation, this model's automated execution, or fulfillment commitments from a service description. The integer output is a recommendation for review; any operational action requires its own confirmed process and approved quantities.

