-
Notifications
You must be signed in to change notification settings - Fork 0
/
data_structures.py
59 lines (43 loc) · 1.44 KB
/
data_structures.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
from abc import ABC, abstractmethod
import heapq
class DataStruct(ABC):
"""Defines an abstract interface for data structures to be used in search methods"""
def __init__(self):
self.list = []
@abstractmethod
def push(self, item, priority=None):
"""Push the given item into the data structure"""
pass
def pop(self):
"""Pop an item out of the data structure"""
return self.list.pop()
def is_empty(self):
"""Returns True iff the data structure is free of any item"""
return len(self.list) == 0
class Queue(DataStruct):
"""
Implements a simple Queue data structure.
A queue uses the First-in-First-out paradigm
"""
def push(self, item, priority=None):
self.list.insert(0, item)
class Stack(DataStruct):
"""
Implements a simple Stack data structure.
A stack uses the First-in-Last-out paradigm
"""
def push(self, item, priority=None):
self.list.append(item)
class PriorityQueue(DataStruct):
"""
Implements a priority queue data structure.
The queue will store each item with a paired priority. That way,
when the pop() method is called, the queue will return the item with
the lowest priority
"""
def push(self, item, priority=None):
pair = (priority, item)
heapq.heappush(self.list, pair)
def pop(self):
priority, item = heapq.heappop(self.list)
return item