Python has a style guide PEP 8 which explains in excruciating detail how to structure your code. I whole heartily recommend skimming through it and follow it.
shortesJobFirst(id, arrival, burst)appears (it is hard to know) to be a function, but functions in python are – according to PEP 8 – written in lowercase seperated by underscores. E.g
shortesJobFirst -> shortest_job_first. However if
shortesJobFirstis a class, you are good =)
You should use the
if __name__ == "__main__":module in your answer.
Your naming practices are somewhat lacking, what does
Pairmean? A better name would perhaps have been
It is tough suggesting better names, as you lack a short explanation of what your code does. This is done by using docstrings
The printing could be improved by using pythons awesome formating options
Why use a class at all when a
namedtuple()can do the same job?
Why implement a sorting function when you can use
Use a basic linter for your code, this ensures you have correct spacings and indents. As mentioned it is common to have two spaces between classes and functions.
from collections import namedtuple from operator import attrgetter def sort_jobs_by_attributes(jobs, attributes): """ This functions sorts the jobs (namedtuples) according to the attribute_lst. If attribute_lst = ("arrival_time", "burst_time", "id") We then first sort by arrival_time, on tie we sort by burst_time, on tie we sort by id """ for attribute in reversed(attributes): jobs.sort(key=attrgetter(attribute)) return jobs JOB_ATTRIBUTES = ("arrival_time", "burst_time", "id") Job = namedtuple("Job", JOB_ATTRIBUTES) if __name__ == "__main__": job_ids = (1, 2, 3, 4) arrival_times = (4, 1, 4, 1) burst_times = (3, 4, 2, 4) jobs = ( Job(*job_details) for job_details in zip(arrival_times, burst_times, job_ids) ) sort_jobs_by_attributes(jobs, JOB_ATTRIBUTES) for job in jobs: print(job)
Side note: you don’t need to provide any key function. The default behavior of tuples (and by extension, namedtuples, since they are a subclass) is to sort element-wise. That means that the first elements of the two tuples are compared, and if there’s a tie then the second elements are compared, and so on. Since the name is the first element, all you need is
from collections import namedtuple JOB_ATTRIBUTES = ("arrival_time", "burst_time", "id") Job = namedtuple("Job", JOB_ATTRIBUTES) if __name__ == "__main__": job_ids = (1, 2, 3, 4) arrival_times = (4, 1, 4, 1) burst_times = (3, 4, 2, 4) jobs = sorted( Job(*job_details) for job_details in zip(arrival_times, burst_times, job_ids) ) for job in jobs: print(job)
Note that implicitly sorting the tuple can be a bit spooky if you later decide the change around the order. In addition to make it harder to see exactly what is being sorted. I will leave it up to you to make the final call on which version is the best.