我需要创建如下内容:
class PriorityQueue(object):
def __init__(self):
self.queue = []
def __str__(self):
return ' '.join([str(i) for i in self.queue])
# for checking if the queue is empty
def isEmpty(self):
return len(self.queue) == []
# for inserting an element in the queue
def insert(self, data):
self.queue.append(data)
# for popping an element based on Priority
def delete(self):
try:
max = 0
for i in range(len(self.queue)):
if self.queue[i] < self.queue[max]:
max = i
item = self.queue[max]
del self.queue[max]
return item
except IndexError:
print()
exit()
就好像它有两个位置的数组(或字典),其中“ A”与一个值关联,而“ D”与其他值关联。然后将这些放置在队列中,稍后再订购。创建,放入队列,获取事件和我已经找到的其他东西的部分,我在下面介绍:
myQueue = PriorityQueue()
myQueue.insert(12)
myQueue.insert(1)
myQueue.insert(14)
myQueue.insert(7)
print(myQueue)
while not myQueue.isEmpty():
print(myQueue.delete())
我已经对其进行了多次测试,并且实际上进行了排序,可以优先获得值,但是我不知道如何放置与“ A”或“ D”字符串关联的值。在python中甚至可能吗?
提供的代码可以将数据放入队列中,如下所示:
sys.path
我需要它以最低的优先级进行活动,并检查它是'A'还是'D'
答案 0 :(得分:0)
看看下面的代码(Python 3):
class PriorityQueue(object):
def __init__(self):
self.queue = []
def __str__(self):
return "\n".join(["\n".join(["{0}: {1}".format(key, pair[key]) for key in pair]) for pair in self.queue])
# for checking if the queue is empty
def isEmpty(self):
return len(self.queue) == 0
# for inserting an element in the queue
def insert(self, data):
if (type(data) == dict) and (len(data) == 1):
new_key = list(data.keys())[0]
if (type(new_key) == str) and (type(data[new_key]) == int):
self.queue.append(data)
# for popping an element based on Priority
def delete(self):
if self.isEmpty():
return [None, None]
max_index = None
max_int = None
max_key = None
for i in range(len(self.queue)):
pair_key = list(self.queue[i].keys())[0]
pair_int = self.queue[i][pair_key]
if (max_index == None) or (pair_int < max_int):
max_index = i
max_int = pair_int
max_key = pair_key
del self.queue[max_index]
return [max_key, max_int]
def main():
myQueue = PriorityQueue()
myQueue.insert({"A": 15})
myQueue.insert({"A": 45})
myQueue.insert({"D": 55})
myQueue.insert({"A": 35})
myQueue.insert({"D": 65})
myQueue.insert({"D": -10})
print(myQueue)
while not myQueue.isEmpty():
key, value = myQueue.delete()
if key:
print("Delete {0} associated to {1}".format(value, key))
每个插入都获得一对string + int(它也支持负值)
输出:
A: 15
A: 45
D: 55
A: 35
D: 65
D: -10
Delete -10 associated to D
Delete 15 associated to A
Delete 35 associated to A
Delete 45 associated to A
Delete 55 associated to D
Delete 65 associated to D