Home > Enterprise >  Rounding a division in a specific way in Python
Rounding a division in a specific way in Python

Time:12-13

How do I round to the thousands a division in a specific way that the top persons pay more?

The division should result in the exact total amount.

I tried this:

total = 245000
print(round(total / 3)

Expected: Person1 = 82000 Person2 = 82000 Person3 = 81000

CodePudding user response:

Divide total by 3 and round up to the next multiple of 1000. Use that for person1 and person2, then subtract those from total to give person3 the remainder.

person1 = person2 = 1000 * ceil(total / 3000)
person3 = total - person1 - person2

CodePudding user response:

Here is an approach that divides the amount by 1000, uses divmod to get the quotient and remainder when dividing the resulting amount by the number of people, then assembles a list where everyone owes 1000 times the quotient. The remainder is used to bump up some of the amounts by 1000:

def divide_amount(amount,num_people):
    amount //= 1000
    q,r = divmod(amount,num_people)
    bills = [1000*q for _ in range(num_people)]
    for i in range(r):
        bills[i]  = 1000
    return bills

print(divide_amount(245000,3)) #[82000, 82000, 81000]

CodePudding user response:

This should work for any number of people.

from math import floor

def rounddown(number, ndigits):
    return 10**-ndigits * floor(number/10**-ndigits)

total = 245000
people = 3

amounts = [rounddown(total/people, -3)   i \
    for i in [1000] * int(total/1000%people)   [0] * (people-int(total/1000%people))]
  • Related