[READ-ONLY] Mirror of https://github.com/mrgnw/python-scripts.
1.7 kB
73 lines
1class PriorityQueue(object):
2
3 items = 0
4 def __init__(self):
5 self.waiters = []
6 self.size = len(self.waiters)
7
8
9 def add(self, q_thing):
10 # Insert based on priority
11 # Prioritize LOW numbers
12 count = 0
13 while count < len(self):
14 # Switched to prioritize LOW numbers
15 if self.waiters[count].priority > q_thing.priority:
16 self.waiters.insert(count, q_thing)
17 return 'Adding ' + str(q_thing)
18 else:
19 count += 1
20 #print 'else'
21
22 else:
23 self.waiters.append(q_thing)
24 return 'Adding ' + str(q_thing)
25
26
27 def top_priority(self):
28 curr_top = None
29 for i in self.waiters:
30 if curr_top < i.priority:
31 curr_top = i.priority
32
33 return curr_top
34
35
36 def remove(self):
37 # Evaluate priority
38 # pop 0 - priority is evaluated in the add() function
39 return self.waiters.pop(0)
40
41
42 def __len__(self):
43 return len(self.waiters)
44
45
46 def __str__(self):
47 strang = ''
48 for x in self.waiters:
49 strang += str(x) + '\n'
50 return strang + '\n'
51
52
53 def __iter__(self):
54 return iter(self.waiters)
55
56
57
58class Q_item(object):
59 def __init__(self, thing, priority):
60 self.thing = thing
61 self.priority = priority
62 self.index = PriorityQueue.items
63 PriorityQueue.items += 1
64
65 def __str__(self):
66 return '%d %s' % (self.priority, self.thing)
67
68 def __add__(self, q2):
69 new_item = Q_item(self.thing, self.priority)
70 new_item.thing += q2.thing
71 new_item.priority += q2.priority
72
73 return new_item