Callum
Callum

Reputation: 321

How do I split an integer up into near-equal amounts in different variables?

I would like to know how to divide any given integer up into any given number of variables while ensuring that the total sum of the value in the variables don't amount to more than the initial integer value.

For example, I would like to divide 5 into 3 different variables, if I just do the below:

var1 = 5 / 3
var2 = 5 / 3
var3 = 5 / 3

I would get each value equating to 1.67 (rounded to 2 decimal places as it's a currency). However, if I was to then do 1.67 * 3 it equals more than 5. Where what I would like is variable 1 and 2 to be 1.67 and then the remaining variable would have the leftover value of 1.66.

Does that make sense?

Upvotes: 1

Views: 1101

Answers (2)

Christian Sloper
Christian Sloper

Reputation: 7510

Here is a general function that solves your problem. It converts the value to cents and distributes them evenly into nr_variables, the remainder are put in the first variables until all spent. The function returns a list of values.

def f(nr_variables, value):

    cents = value*100

    base = cents//nr_variables
    rem = int(cents%nr_variables)

    return [(base+1)/100]*rem + [base/100]*(nr_variables-rem)

this can be used like this:

f(3,5)

and gives:

[1.67, 1.67, 1.66]

if you want to assign the list to variables like you do in your question, you can do like this:

var1,var2,var3 = f(3,5)

Upvotes: 3

Tim
Tim

Reputation: 2231

If you don't want to loose precision in numbers, consider using Fraction:

from fractions import Fraction

var1 = Fraction(5, 3)
var2 = Fraction(5, 3)
var3 = Fraction(5, 3)

print(round(var1, 2))
print(round(var2, 2))
print(round(var3, 2))
print(var1 * 3)

result:

1.67
1.67
1.67
5

Upvotes: -1

Related Questions