0

I am trying to write a python script to divide the students registered into classes. Let's say I have 81 students and the max capacity is 20 students I want to get 5 classes with 16-17 student each, not 5 classes with 20 20 20 20 and 1 student alone.

Thanks a lot!

Edit : i solved it. here is the algorithm if anyone is interested

import math

def partition_students(students, max_capacity):
    students.sort(key=lambda student: student.last_name)

    num_students = len(students)
    num_classes = math.ceil(num_students / max_capacity)
    num_students_per_class = math.ceil(num_students / num_classes)

    classes = [[] for _ in range(num_classes)]  # Initialize classes with empty lists

    class_index = -1

    for i, student in enumerate(students):
        if i % num_students_per_class == 0:
            class_index = (class_index + 1) % num_classes  # Update class_index

        classes[class_index].append(student)

    return classes
  • Please update your question with the code you have tried. – quamrana Jun 13 '23 at 15:58
  • 1
    I encourage you to make an effort and try to write your own code. Even if it's full mistakes, we'll correct you and that way you will learn faster – Obaskly Jun 13 '23 at 15:59
  • Divide the number of students by 20. Round this up to get the number of classes. Then divide the students by the number of classes and round this down. Finally, distribute the remainder among the classes. – Barmar Jun 13 '23 at 16:08
  • 1
    I think this question may help: https://stackoverflow.com/questions/2130016/splitting-a-list-into-n-parts-of-approximately-equal-length – dDiaz Jun 13 '23 at 16:40
  • @Mohamed Your solution include a sort. It was not asked for. Number of students per class are 17,17,17,17,13. It's not what you asked for. Your program use student.last_name; it wasn't mentioned in your question. For these 3 reasons, I consider your solution is not a good solution and I downvote. – user3435121 Jun 14 '23 at 16:08

1 Answers1

0

Try this :

def split_students(students):
    classes = (students-1)// 20 + 1
    output = [students//classes] * classes
    remainder = students - sum(output)
    for i in range(remainder):
        output[i] += 1
    return output

You pass the amount of students and it returns a list containing the amount of students per class. I have assumed the classroom is max 20 students.

Does it help ?

LioWal
  • 56
  • 2