Home > Software engineering >  Creating subgroups with balanced averages in Python
Creating subgroups with balanced averages in Python

Time:10-12

I have 18 students in a class with the following scores, broken into the following sets:

high = [401.2,398.8,350.2,288.3,263.3,249.8]
mid = [249.6,246.7,244.2,239.8,211.4,204.9]
low = [203.5,165.9,157.7,135.3,129.1,100.9]

I want to create groups from these sets. Each group should have a member from the high, medium, and low sets, and the average score of these groups should be as balanced as possible. I've been trying some ideas using itertools, but haven't quite got it yet.

CodePudding user response:

What if we choose a random index from each list till they run out of entries like this?

high = [401.2,398.8,350.2,288.3,263.3,249.8]
mid = [249.6,246.7,244.2,239.8,211.4,204.9]
low = [203.5,165.9,157.7,135.3,129.1,100.9]

groups = []

while len(high)>0 and len(mid)>0 and len(low)>0:
    h = high.pop(high.index(random.choice(high)))
    m = mid.pop(mid.index(random.choice(mid)))
    l = low.pop(low.index(random.choice(low)))
    groups.append((h, m, l))

CodePudding user response:

Assuming the groups are ordered, a fast approach that could be fairly balanced would be to group each subgroup with the following method:

Pair the high and low iterating in opposite directions: (e.g. the first subgroup will contain 401.2 and 100.9) For the mid group, iterate over it normally, but start halfway through the set.

This method will only work if the dataset is linear and without much deviation.

high = [401.2,398.8,350.2,288.3,263.3,249.8]
mid = [249.6,246.7,244.2,239.8,211.4,204.9]
low = [203.5,165.9,157.7,135.3,129.1,100.9]

subgroups = []
for i in range(len(high)): # ASSUMPTION: all lists are same length, and ordered
    subgroup = []

    # Add the high group members in order of highest to lowest
    subgroup.append(high[i])
    # Add the middle value, shifted by half the length of the group's
    subgroup.append(mid[(i   len(high)//2) % len(high)]) # Use modulo to loop over list cyclically
    # Add members of low in reverse order (last member of low is in subgroup 0)
    subgroup.append(low[-i - 1])

    subgroups.append(subgroup)
  • Related