This code implements priority queues for job processing. It take first input in line 1 as workers and second input in line 1 as no of job and inputs in line 2 are t(i) time take to process (i)th job.
import queue as Q
from collections import namedtuple
AssignedJob = namedtuple("AssignedJob", ["worker", "started_at"])
def cmp(a,b):
if a >= b:
return a
else :
return b
def assign_jobs(n_workers, jobs):
result = []
pq = Q.PriorityQueue()
for i in range(n_workers):
pq.put(Worker(i))
for j in range(len(jobs)):
f_thread = pq.get()
result.append(AssignedJob(f_thread.id, f_thread.nextFreeTime))
f_thread.nextFreeTime += jobs[j]
pq.put(f_thread)
return result
class Worker(object):
def __init__(self, id):
self.id = id
self.nextFreeTime = 0
def __cmp__(self, other):
if(self.nextFreeTime == other.nextFreeTime):
return cmp(self.id, other.id)
else:
return cmp(self.nextFreeTime, other.nextFreeTime)
def main():
n_workers, n_jobs = map(int, input().split())
jobs = list(map(int, input().split()))
assert len(jobs) == n_jobs
assigned_jobs = assign_jobs(n_workers, jobs)
for job in assigned_jobs:
print(job.worker, job.started_at)
if __name__ == "__main__":
main()
This is the error while running this program with input
2 5
1 2 3 4 5
Traceback (most recent call last):
File "C:/Users/vk911/.PyCharmCE2019.2/config/scratches/scratch_1.py", line 61, in <module>
job_queue.solve()
File "C:/Users/vk911/.PyCharmCE2019.2/config/scratches/scratch_1.py", line 55, in solve
self.fast_assign_jobs()
File "C:/Users/vk911/.PyCharmCE2019.2/config/scratches/scratch_1.py", line 33, in fast_assign_jobs
pq.put(self.Worker(i))
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.2544.0_x64__qbz5n2kfra8p0\lib\queue.py", line 149, in put
self._put(item)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.2544.0_x64__qbz5n2kfra8p0\lib\queue.py", line 233, in _put
heappush(self.queue, item)
TypeError: '<' not supported between instances of 'Worker' and 'Worker'