Advertisement
Telegram ads for your business · TCA Media
Advertisement
Telegram ads for your business · TCA Media
IT

How to Distribute Costs Across Boxes Using Python

A Python algorithm distributes delivery costs across boxes so that the sum of the lines matches the original invoice, with the remainder allocated to boxes with the largest fractional shares.

02 Dec, 17:00Read in Russian
git.ru

When fractional shares are rounded separately, a discrepancy arises: out of 100 kopecks in delivery costs for three boxes of equal weight, the result is 33 + 33 + 33, which is 1 kopeck less than the original sum. The Decimal module allows for more precise handling of fractions, but it does not determine which line should receive the remainder.

The solution is built in two stages. First, the integer part of the share is calculated for each box: the total amount is multiplied by the weight, and the result is divided by the total weight. Then, the remaining kopecks are allocated to boxes in descending order of their fractional remainders. If the remainders are equal, a predefined order is used—in the example, the box identifier. Therefore, rearranging the rows in the input data does not change the final result.

For instance, when weights are equal, the distribution of 100 kopecks will allocate 34 kopecks to box A and 33 kopecks each to boxes B and C. A box with zero weight receives a zero share. The function also rejects negative amounts and weights, and returns an error if the total weight is zero.

This method is suitable only for a total amount that needs to be divided according to given weights. Fixed fees per box, volumetric tariffs, and surcharges should first be assigned to specific lines, and only the remaining costs should be included in the general distribution. Refunds and negative adjustments require a separate rule.

Advertisement
Telegram ads for your business · TCA Media