forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue_on_two_stacks.py
138 lines (115 loc) · 2.93 KB
/
queue_on_two_stacks.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
133
134
135
136
137
138
"""Queue implementation using two stacks"""
from collections.abc import Iterable
from typing import Generic, TypeVar
_T = TypeVar("_T")
class Queue(Generic[_T]):
def __init__(self, iterable: Iterable[_T] | None = None) -> None:
"""
>>> queue1 = Queue()
>>> str(queue1)
'<[]>'
>>> queue2 = Queue([10, 20, 30])
>>> str(queue2)
'<[10, 20, 30]>'
>>> queue3 = Queue((i**2 for i in range(1, 4)))
>>> str(queue3)
'<[1, 4, 9]>'
"""
self._stack1: list[_T] = [] if iterable is None else list(iterable)
self._stack2: list[_T] = []
def put(self, item: _T) -> None:
"""
Put `item` into the Queue
>>> queue = Queue()
>>> queue.put(10)
>>> queue.put(20)
>>> len(queue) == 2
True
>>> str(queue)
'<[10, 20]>'
"""
self._stack1.append(item)
def get(self) -> _T:
"""
Get `item` from the Queue
>>> queue = Queue()
>>> for i in (10, 20, 30):
... queue.put(i)
>>> len(queue)
3
>>> queue.get()
10
>>> queue.get()
20
>>> len(queue) == 1
True
>>> queue.get()
30
>>> queue.get()
Traceback (most recent call last):
...
IndexError: Queue is empty
"""
# To reduce number of attribute look-ups in `while` loop.
stack1_pop = self._stack1.pop
stack2_append = self._stack2.append
if not self._stack2:
while self._stack1:
stack2_append(stack1_pop())
if not self._stack2:
raise IndexError("Queue is empty")
return self._stack2.pop()
def size(self) -> int:
"""
Returns the length of the Queue
>>> queue = Queue()
>>> queue.size()
0
>>> queue.put(10)
>>> queue.put(20)
>>> queue.size()
2
>>> queue.get()
10
>>> queue.size() == 1
True
"""
return len(self)
def __str__(self) -> str:
"""
>>> queue = Queue()
>>> str(queue)
'<[]>'
>>> queue.put(10)
>>> str(queue)
'<[10]>'
>>> queue.put(20)
>>> str(queue)
'<[10, 20]>'
>>> queue.get()
10
>>> queue.put(30)
>>> str(queue) == '<[20, 30]>'
True
"""
return f"<{self._stack2[::-1] + self._stack1}>"
def __len__(self) -> int:
"""
>>> queue = Queue()
>>> for i in range(1, 11):
... queue.put(i)
...
>>> len(queue) == 10
True
>>> for i in range(2):
... queue.get()
...
1
2
>>> len(queue) == 8
True
"""
return len(self._stack1) + len(self._stack2)
if __name__ == "__main__":
from doctest import testmod
testmod()