【问题标题】:priority queue. This error is shown while compiling with python 3.7 [duplicate]优先队列。使用 python 3.7 编译时显示此错误 [重复]
【发布时间】:2020-12-19 17:05:42
【问题描述】:

此代码实现了作业处理的优先级队列。它将第 1 行的第一个输入作为工人,第 1 行的第二个输入作为没有工作,第 2 行的输入是处理第 (i) 个工作所需的 t(i) 时间。

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()

这是使用输入运行此程序时的错误

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'

【问题讨论】:

标签: python


【解决方案1】:

__cmp__ 在 python3 中不受支持。 如需支持比较运算符,请根据用例使用__lt____gt__ 或其他运算符。

更详细的解释在this answer中给出

【讨论】:

  • 好的..感谢您的帮助。我已经在上面定义了 cmp ......那不行吗?
  • 它只适用于python2
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-13
  • 1970-01-01
  • 2019-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-10
相关资源
最近更新 更多