# [FIXED] Sorting dynamic data with multiple parameters and distribute them equally in python dango

## Issue

I wanted to sort a list of users based on some field parameters and distribute them into a list equally, I am trying to make an automated way to help schools distribute students into classrooms as part of a bigger system.

Explaining functionality:

let’s assume there are 100 students registered for 4th grade and within the grade, there are 4 sections{A, B, C, D}, when the function is run I want to take all the students registered for 4th grade and put them in a list afterward the function should iterate through the list and try(because there will be closely related values and might not be exactly similar) to equally distribute them in 4 lists(number of sections) or directly save them with there respective section instance,
the effect should in some way resemble a magnet in which similarities repulse each other and difference attracts each other until the lists are refined to the best they can be.

it’s not much of a problem if the method is slow because there will not be a lot of students in one list since it’s going to execute at grade level, please point me to a resource, share a snipper or explain the ways I can implement it.
5 student:

``````Student-1:{
age:12,height:1.2m, sex:MALE
}

Student-2:{
age:11,height:1.2m, sex:FEMALE
}
Student-3:{
age:13,height:1.3m, sex:MALE
}
Student-4:{
age:11,height:1.24m, sex:FEMALE
}
Student-5:{
age:13,height:1.2m, sex:MALE
}
``````

expected outPut:

``````section-1:{
Student-1,
Student-3
}
section-2:{
Student-5,
Student-4
}
section-3:{
Student-2
}
``````

so if there are more similarities than differences ie `Similar:{age = True, height=True, sex=False}` == `similarities > difference`, and are overall more similar compared to the other instances it should be put in the next class

## Solution

you have to write a "weight" function, based on the attributes you have – and then tune this to the weight you want each attribute. Then sort everyone by using this "weight" function, so that the similar ones are actually closest (the reverse of what you want).

Once you get there, you slice the resulting list with all students, so that the first is in A, the second is in B, and so forth.

This seems to be the most sane way – otherwise you may end up getting the extremes in a single group, like the tallest and shortest student in the same group, always.

The weight function might be something like:

``````import statiscs
import itertools

average_height = statistics.median(student.height for student in students)
def weight(student):
gender = 100 if student.gender == "female" else 0
height = 30 * (student.height - average_height)
...
return gender + height + ....
students.sort(key=weight)
groups = {}
for group, student in zip(itertools.cycle("ABCD"), students):
groups.setdefault(group, []).append(student)
return groups

``````