迭代heapq并更新任意数量的值:需要我调用heapify或使用新堆

时间:2015-11-19 15:27:24

标签: python heap

我有一个堆,我们称之为qq充满了具有通过__cmp__函数排序的值的对象。我想迭代堆并更新这样的值:

def update_loads(rem_volume):
    global q
    for load in q:
        if rem_volume < load.cost :
            load.reduceAvail()
    heapq.heapify(q)

这是对的吗?我希望整个过程最多只能O(load)所以如果我在堆中执行我需要做的事情,最后调用heapify应该只使用一次。我不确定heapify是否会起作用,实际上可能需要O(load log(load))

class Load:
    'class for load'
    loadCount=0

    def __init__(self,s,f,sn,c):
        self.ts_S=s
        self.ts_F=f
        self.slotsNeeded = sn
        self.cost = c
        self.slotsAvail = f-s
        self.ID = Load.loadCount
        Load.loadCount += 1

    def N_L(self):
         return Load.loadCount

    def display(self):
         print("Start Time: %s End Time: %s, height: %s, cost: %s"
          %(self.ts_S,self.ts_F,self.height,self.cost))

    def __cmp__(self,other):
        val = 1-(self.slotsNeeded/self.slotsAvail)
        otherval = 1-(other.slotsNeeded/other.slotsAvail)
        return cmp(val, otherval)

    def reduceNeeded(self):
         self.slotsNeeded -= 1

    def reduceAvail(self):
        self.slotsAvail -= 1

def load_heap():
    global max_cost
    q= []                              #create heap                                                                                         
    with open(loadConfig,'r') as ins:  # open file with loads                                                                               
        for line in ins:               #read line by line                                                                                   
            if line[0] != '#':         #comments                                                                                            
                 e = line.split(',')      # parse file                                                                                         
                                   #add load to heap                                                                                    
                 heapq.heappush(q,Load(int(e[0]),
                                  (inte[1]),
                                  int(e[2]),
                                  int(e[3])))
                 if int(e[3]) > max_cost:
                     max_cost = int(e[3])
     return q

所以代码是上下文的对象类以及如何构建堆。无论如何,我希望以有效的方式做到这一点。有什么建议吗?

由于

0 个答案:

没有答案