Skip to content
Advertisement

To group number of data upto a certain limit

If anyone could help me out to solve this problem, that would be greatly appreciated. Here I have a list of weights (kg) of a few samples.

weight_list = [0.2, 0.4, 1.0, 0.7, 0.1, 0.4, 0.9, 0.1, 0.2, 0.4, 0.2, 0.1]

The maximum weight that could be for any sample is 1 kg. I need to sum sample weights until the total mass is not exceeding 1 kg. For instance, this is what I expect after summing the weights of samples based on the given condition. 

grouped_list = [0.6, 1.0, 0.8, 0.4, 1.0, 0.9]

this is what I have so far, but it loops over infinitely.

weight_list = [0.2, 0.4, 1.0, 0.7, 0.1, 0.4, 0.9, 0.1, 0.2, 0.4, 0.2, 0.1]
grouped_list = []
for weight in weight_list:
    total = 0
    while total <= 1:
        total += weight
        if total > 1:
            total -= weight
            grouped_list.append(total)
            total = 0
        else:
            grouped_list.append(total)

I am open to entirely new methods as well, if there any module or easy way to group this, please kindly assist me.

Advertisement

Answer

This works, you are currently looping for the same weight everytime, instead, you should iterate the list like this:

weight_list = [0.2, 0.4, 1.0, 0.7, 0.1, 0.4, 0.9, 0.1, 0.2, 0.4, 0.2, 0.1]
grouped_list = []
total, count = 0, 0
# increment counter over the weight list
while count < len(weight_list):
    total += weight_list[count]
    if total > 1:
        # add the weight if it recently exceeded 1 by subtracting recent weight
        total -= weight_list[count]
        # round to 1 decimal point (due to floating point math)
        grouped_list.append(round(total, 1))
        total = 0
    else:
        count += 1
# add the left-over total if < 1
if total < 1:
    grouped_list.append(round(total, 1))
print(grouped_list)

gives

[0.6, 1.0, 0.8, 0.4, 1.0, 0.9]
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement