Skip to content

Instantly share code, notes, and snippets.

@brabect1
Last active June 24, 2024 04:40
Show Gist options
  • Save brabect1/0853367e7952855357188012586d1a60 to your computer and use it in GitHub Desktop.
Save brabect1/0853367e7952855357188012586d1a60 to your computer and use it in GitHub Desktop.
distributing an integer total into n integers of almost the same value #python

Distributing total into evenly sized integers

A snippet showing how to distribute even integral weights (e.g. percantage).

from random import randrange

def distribute(n,total=100):
    if (n > total):
        return None

    s = 0;
    l = [];
    for i in range(0,n):
        p = round (total * (i+1) / n) - s;
        s += p;
        l.append(p);
    return l;


for x in range(1,10):
    t = randrange(50,100);
    l = distribute(x, total=t);
    print(f"{x}: {l} = {sum(l)} ? {t}");

Example output:

1: [57] = 57 ? 57
2: [44, 44] = 88 ? 88
3: [31, 30, 31] = 92 ? 92
4: [15, 15, 14, 15] = 59 ? 59
5: [20, 19, 20, 19, 20] = 98 ? 98
6: [13, 14, 13, 13, 14, 13] = 80 ? 80
7: [8, 9, 8, 8, 8, 9, 8] = 58 ? 58
8: [8, 8, 9, 8, 8, 9, 8, 8] = 66 ? 66
9: [9, 8, 9, 8, 9, 8, 9, 8, 9] = 77 ? 77
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment