|
| 1 | +import heapq |
| 2 | +import argparse |
| 3 | + |
| 4 | +class PersistentPriorityQueue: |
| 5 | + """ |
| 6 | + A persistent priority queue implemented using a text file for storage. |
| 7 | + """ |
| 8 | + def __init__(self, file_path): |
| 9 | + """ |
| 10 | + Initialize the persistent priority queue. |
| 11 | +
|
| 12 | + Parameters: |
| 13 | + - file_path (str): The path to the text file used for storage. |
| 14 | + """ |
| 15 | + self.file_path = file_path |
| 16 | + |
| 17 | + def push(self, item, priority): |
| 18 | + """ |
| 19 | + Push an item with a given priority into the queue. |
| 20 | +
|
| 21 | + Parameters: |
| 22 | + - item: The item to push into the queue. |
| 23 | + - priority: The priority associated with the item. |
| 24 | + """ |
| 25 | + with open(self.file_path, 'a') as file: |
| 26 | + file.write(f"{priority} {item}\n") |
| 27 | + |
| 28 | + def pop(self): |
| 29 | + """ |
| 30 | + Pop the item with the highest priority from the queue and remove it. |
| 31 | +
|
| 32 | + Returns: |
| 33 | + - item: The item with the highest priority. |
| 34 | + """ |
| 35 | + # Read all items from the file and store them in a list of (priority, item) tuples |
| 36 | + items = [] |
| 37 | + with open(self.file_path, 'r') as file: |
| 38 | + for line in file: |
| 39 | + priority, item = line.strip().split(' ', 1) |
| 40 | + items.append((int(priority), item)) |
| 41 | + |
| 42 | + if not items: |
| 43 | + raise IndexError("Queue is empty") |
| 44 | + |
| 45 | + # Find the item with the highest priority |
| 46 | + highest_priority_item = min(items, key=lambda x: x[0]) |
| 47 | + |
| 48 | + # Remove the item from the list and update the file |
| 49 | + items.remove(highest_priority_item) |
| 50 | + with open(self.file_path, 'w') as file: |
| 51 | + for priority, item in items: |
| 52 | + file.write(f"{priority} {item}\n") |
| 53 | + |
| 54 | + return highest_priority_item[1] |
| 55 | + |
| 56 | + def peek(self): |
| 57 | + """ |
| 58 | + Get the item with the highest priority without removing it from the queue. |
| 59 | +
|
| 60 | + Returns: |
| 61 | + - item: The item with the highest priority. |
| 62 | + """ |
| 63 | + items = [] |
| 64 | + with open(self.file_path, 'r') as file: |
| 65 | + for line in file: |
| 66 | + priority, item = line.strip().split(' ', 1) |
| 67 | + items.append((int(priority), item)) |
| 68 | + |
| 69 | + if not items: |
| 70 | + raise IndexError("Queue is empty") |
| 71 | + |
| 72 | + highest_priority_item = min(items, key=lambda x: x[0]) |
| 73 | + return highest_priority_item[1] |
| 74 | + |
| 75 | + def is_empty(self): |
| 76 | + """ |
| 77 | + Check if the queue is empty. |
| 78 | +
|
| 79 | + Returns: |
| 80 | + - bool: True if the queue is empty, False otherwise. |
| 81 | + """ |
| 82 | + with open(self.file_path, 'r') as file: |
| 83 | + return not any(True for line in file) |
| 84 | + |
| 85 | + def change_priority(self, target_item, new_priority): |
| 86 | + """ |
| 87 | + Change the priority of a specific item in the queue. |
| 88 | +
|
| 89 | + Parameters: |
| 90 | + - target_item: The item whose priority you want to change. |
| 91 | + - new_priority: The new priority to assign to the item. |
| 92 | + """ |
| 93 | + items = [] |
| 94 | + updated_items = [] |
| 95 | + |
| 96 | + # Read all items from the file and store them in a list of (priority, item) tuples |
| 97 | + with open(self.file_path, 'r') as file: |
| 98 | + for line in file: |
| 99 | + priority, item = line.strip().split(' ', 1) |
| 100 | + items.append((int(priority), item)) |
| 101 | + |
| 102 | + # Find the target item and update its priority |
| 103 | + found = False |
| 104 | + for priority, item in items: |
| 105 | + if item == target_item: |
| 106 | + updated_items.append((new_priority, item)) |
| 107 | + found = True |
| 108 | + else: |
| 109 | + updated_items.append((priority, item)) |
| 110 | + |
| 111 | + if not found: |
| 112 | + raise ValueError(f"Item '{target_item}' not found in the queue.") |
| 113 | + |
| 114 | + # Write the updated items back to the file |
| 115 | + with open(self.file_path, 'w') as file: |
| 116 | + for priority, item in updated_items: |
| 117 | + file.write(f"{priority} {item}\n") |
| 118 | + |
| 119 | + def reorder_priorities(self): |
| 120 | + """ |
| 121 | + Reorder the priorities in the queue to be consecutive starting from 1. |
| 122 | + """ |
| 123 | + items = [] |
| 124 | + updated_items = [] |
| 125 | + |
| 126 | + # Read all items from the file and store them in a list of (priority, item) tuples |
| 127 | + with open(self.file_path, 'r') as file: |
| 128 | + for line in file: |
| 129 | + priority, item = line.strip().split(' ', 1) |
| 130 | + items.append((int(priority), item)) |
| 131 | + |
| 132 | + # Sort the items by their existing priorities |
| 133 | + items.sort(key=lambda x: x[0]) |
| 134 | + |
| 135 | + # Assign new consecutive priorities starting from 1 |
| 136 | + new_priority = 1 |
| 137 | + for _, item in items: |
| 138 | + updated_items.append((new_priority, item)) |
| 139 | + new_priority += 1 |
| 140 | + |
| 141 | + # Write the updated items back to the file |
| 142 | + with open(self.file_path, 'w') as file: |
| 143 | + for priority, item in updated_items: |
| 144 | + file.write(f"{priority} {item}\n") |
| 145 | + |
| 146 | + def print_queue(self): |
| 147 | + """ |
| 148 | + Print the entire contents of the priority queue. |
| 149 | + """ |
| 150 | + with open(self.file_path, 'r') as file: |
| 151 | + print(file.read()) |
| 152 | + |
| 153 | + |
| 154 | + def insert_and_shift_up(self, item, target_priority): |
| 155 | + """ |
| 156 | + Insert an item at a specific priority and shift up the priorities of all subsequent items by 1. |
| 157 | +
|
| 158 | + Parameters: |
| 159 | + - item (str): The item to insert. |
| 160 | + - target_priority (int): The desired priority for the item. |
| 161 | +
|
| 162 | + Returns: |
| 163 | + None |
| 164 | +
|
| 165 | + Note: Feel free to use the reorder method after to make them consecutive |
| 166 | + """ |
| 167 | + items = [] |
| 168 | + |
| 169 | + # Read all items from the file into a list of (priority, item) tuples |
| 170 | + with open(self.file_path, 'r') as file: |
| 171 | + for line in file: |
| 172 | + priority, existing_item = line.strip().split(' ', 1) |
| 173 | + items.append((int(priority), existing_item)) |
| 174 | + |
| 175 | + # Increment the priorities of items that are >= target_priority |
| 176 | + items = [(p + 1 if p >= target_priority else p, i) for p, i in items] |
| 177 | + |
| 178 | + # Insert the new item |
| 179 | + items.append((target_priority, item)) |
| 180 | + |
| 181 | + # Sort the updated items |
| 182 | + items.sort(key=lambda x: x[0]) |
| 183 | + |
| 184 | + # Write the updated items back to the file |
| 185 | + with open(self.file_path, 'w') as file: |
| 186 | + for priority, existing_item in items: |
| 187 | + file.write(f"{priority} {existing_item}\n") |
| 188 | + |
| 189 | + |
| 190 | + |
| 191 | +# Example usage: |
| 192 | +if __name__ == "__main__": |
| 193 | + pq = PersistentPriorityQueue("priority_queue.txt") |
| 194 | + |
| 195 | + parser = argparse.ArgumentParser(description="Persistent Priority Queue") |
| 196 | + parser.add_argument("--file", type=str, default="priority_queue.txt", help="Path to the storage file") |
| 197 | + |
| 198 | + group = parser.add_mutually_exclusive_group() |
| 199 | + group.add_argument("--push", nargs=2, metavar=("item", "priority"), help="Push an item with a priority") |
| 200 | + group.add_argument("--pop", action="store_true", help="Pop the highest priority item") |
| 201 | + group.add_argument("--peek", action="store_true", help="Peek at the highest priority item") |
| 202 | + group.add_argument("--is_empty", action="store_true", help="Check if the queue is empty") |
| 203 | + group.add_argument("--change_priority", nargs=2, metavar=("item", "new_priority"), help="Change the priority of an item") |
| 204 | + group.add_argument("--reorder_priorities", action="store_true", help="Reorder priorities in the queue") |
| 205 | + group.add_argument("--print_queue", action="store_true", help="Print the entire queue") |
| 206 | + |
| 207 | + group2 = parser.add_mutually_exclusive_group() |
| 208 | + group2.add_argument("--insert_and_shift_up", nargs=2, metavar=("item", "target_priority"), help="Insert an item and shift up priorities") |
| 209 | + |
| 210 | + args = parser.parse_args() |
| 211 | + |
| 212 | +if args.push: # Example: --push "Task C" 3 |
| 213 | + item, priority = args.push |
| 214 | + pq.push(item, int(priority)) |
| 215 | +elif args.pop: # Example: --pop |
| 216 | + item = pq.pop() |
| 217 | + print(f"Popped item: {item}") |
| 218 | +elif args.peek: # Example: --peek |
| 219 | + item = pq.peek() |
| 220 | + print(f"Peeked item: {item}") |
| 221 | +elif args.is_empty: # Example: --is_empty |
| 222 | + is_empty = pq.is_empty() |
| 223 | + print(f"Queue is empty: {is_empty}") |
| 224 | +elif args.change_priority: # Example: --change_priority "Task A" 2 |
| 225 | + item, new_priority = args.change_priority |
| 226 | + pq.change_priority(item, int(new_priority)) |
| 227 | +elif args.reorder_priorities: # Example: --reorder_priorities |
| 228 | + pq.reorder_priorities() |
| 229 | +elif args.print_queue: # Example: --print_queue |
| 230 | + pq.print_queue() |
| 231 | +elif args.insert_and_shift_up: # Example: --insert_and_shift_up "Task D" 2 |
| 232 | + item, target_priority = args.insert_and_shift_up |
| 233 | + pq.insert_and_shift_up(item, int(target_priority)) |
0 commit comments