p0nts
p0nts

Reputation: 63

Split number into rounded numbers

Is there a library that can split a number into multiple parts, but makes sure all the parts are rounded numbers?

For example, splitting 100 into 3 would be 33.33, but I would like it to be rounded and make sure the total sum stays as 100 also:

[34 33 33]

Upvotes: 2

Views: 2040

Answers (4)

toti08
toti08

Reputation: 2454

Assuming that your inputs are integers, another approach could be the following:

def divNum(num, parts):
    #Compute integer division
    p = num/parts

    #Check if there's a reminder
    if p*parts == num:
        #No reminder, return the integers as they are
        return [p]*parts
    else:
        #Compute how much is the reminder
        missing = num - p*parts                  
        return [p+1]*missing + [p]*(parts-missing)

Edit: as suggested there's no need to check if the remainder is zero or not, so my code could be simplified as:

def divNum(num, parts):
    p = num/parts
    missing = num - p*parts                  
    return [p+1]*missing + [p]*(parts-missing)

Upvotes: 1

Håken Lid
Håken Lid

Reputation: 23064

You can use the builtin function divmod for this. Since all this function does is simple arithmetic, I'm using single letter variable names.

def parts(a, b):
    q, r = divmod(a, b)
    return [q + 1] * r + [q] * (b - r)

The return value is a list with the larger parts first.

>>> parts(100, 3)
[34, 33, 33]

>>> parts(100, 7)
[15, 15, 14, 14, 14, 14, 14]

Upvotes: 13

Albin Paul
Albin Paul

Reputation: 3419

Well I think this is what you wanted

number=100
div=3
#find the dividend of the number in this case 33

dividend=int(number/div)
#makea a list to store the numbers

listofrequirednumbers=[dividend]*div
#find the numbers remaining from 100 ie 100-33*3=1 one 
#one number should be added to the list 

for i in range(number%div):
    listofrequirednumbers[i]+=1

print(listofrequirednumbers)

Output

[34, 33, 33]

Upvotes: 2

jihan1008
jihan1008

Reputation: 360

I think you can implement it without libraries.

1) If the number n is divided by 3, then the output would be [n/3, n/3, n/3]

2) If the number n = 3k + 1(k>=0), then the output would be [(n/3)+1, n/3, n/3]

3) Otherwise, the output would be [(n/3)+1, (n/3)+1, n/3]

Upvotes: 0

Related Questions