Python Forum

Full Version: Balance integer list into multiple list of fixed value
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all,

I am trying to split the given list into multuple lists where the value limit for such splitted-list will be 10.

For example, given a list, eg. init_list = [1, 2, 3, 1, 7, 4, 5, 11], I am trying to split init_list into 3 different lists where each list each list only holds up to a max value of 10.
It will either fills up with as many as integers that adds up to 10, or integers closest to 10..

And if there are any integers not used, those integers will be appended in another list and so the results would be something as follows:

list01 = [1, 1, 2, 3, 4]
list02 = [7]
list03 = [5]

# unused
unused = [11]
So far I have managed to get it to split the list into 3 different lists, but I am unable to get the portion of setting the max value of 10 or, appending only the integer(s) closest to 10..
init_list = [1, 2, 3, 1, 7, 4, 5, 11]

def split_list(given_list, n):
    result = [[] for i in range(n)]
    sums   = [0]*n
    i = 0
    for e in given_list:
        result[i].append(e)
        sums[i] += e
        i = sums.index(min(sums))
    return result

split_list(init_list, 3)
Not exactly sure if this is the right way to approach this, or if anyone can kindly advise any other topics that I can try looking into?
Try this: start with two empty lists (the list of lists, and the first sub-list). Have a total that is zero.

Now loop through the numbers in the loop you were given. If the number plus the total is ten or less, append that number to the sub-list and add it to the total. Otherwise, append the sub-list to the list of lists, start a new sub-list with that number, and reset the total.

At the end of the loop you will have a sub-list left over. Append that to the list of lists. That should be that.