Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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*100base = 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)

Solution 2:

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

Post a Comment for "How Do I Split An Integer Up Into Near-equal Amounts In Different Variables?"