0

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'
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • Please update your question with the full error traceback. – quamrana Dec 19 '20 at 17:07
  • 1
    Does this answer your question? [Why can't I use the method \_\_cmp\_\_ in Python 3 as for Python 2?](https://stackoverflow.com/questions/8276983/why-cant-i-use-the-method-cmp-in-python-3-as-for-python-2) – L.Grozinger Dec 19 '20 at 17:24

1 Answers1

0

__cmp__ is not supported in python3. for supporting comparison operators, use __lt__ ,__gt__ or others based on use case.

More detailed explanation given in this answer

Adithya
  • 1,688
  • 1
  • 10
  • 18