forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue_on_list.py
132 lines (106 loc) · 2.86 KB
/
queue_on_list.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
"""Queue represented by a Python list"""
from typing import Any
class Queue:
def __init__(self) -> None:
self.entries: list[Any] = []
def __str__(self) -> str:
"""
>>> queue = Queue()
>>> str(queue)
'<>'
>>> queue.put(10)
>>> queue.put(20)
>>> queue.put(30)
>>> str(queue)
'<10, 20, 30>'
"""
return "<" + str(self.entries)[1:-1] + ">"
def __len__(self) -> int:
"""
>>> queue = Queue()
>>> queue.put(10)
>>> queue.put(20)
>>> queue.put(30)
>>> len(queue)
3
"""
return len(self.entries)
def put(self, item: Any) -> None:
"""Put `item` to the Queue
>>> queue = Queue()
>>> queue.put(10)
>>> str(queue)
'<10>'
>>> queue.put(20)
>>> str(queue)
'<10, 20>'
>>> len(queue)
2
"""
self.entries.append(item)
def get(self) -> Any:
"""Get `item` from the Queue
>>> queue = Queue()
>>> queue.put(10)
>>> queue.get() == 10
True
>>> len(queue) == 0
True
>>> queue.get()
Traceback (most recent call last):
...
IndexError: Queue is empty
"""
if not self.entries:
raise IndexError("Queue is empty")
return self.entries.pop(0)
def rotate(self, rotation: int) -> None:
"""Rotate the items of the Queue `rotation` times
>>> queue = Queue()
>>> for i in (10, 20, 30, 40):
... queue.put(i)
...
>>> str(queue)
'<10, 20, 30, 40>'
>>> queue.rotate(1)
>>> str(queue)
'<20, 30, 40, 10>'
>>> queue.rotate(2)
>>> str(queue)
'<40, 10, 20, 30>'
"""
# An optimization to reduce the number of attribute look-ups in the for-loop.
put = self.entries.append
get = self.entries.pop
for _ in range(rotation):
put(get(0))
def get_front(self) -> Any:
"""Get the front item from the Queue
>>> queue = Queue()
>>> for i in (10, 20, 30):
... queue.put(i)
...
>>> queue.get_front()
10
>>> len(queue) == 3
True
"""
return self.entries[0]
def size(self) -> int:
"""Returns the length of the Queue
>>> queue = Queue()
>>> queue.put(10)
>>> queue.size()
1
>>> queue.put(20)
>>> queue.size()
2
>>> queue.get()
10
>>> queue.size() == 1
True
"""
return len(self.entries)
if __name__ == "__main__":
from doctest import testmod
testmod()