-
Notifications
You must be signed in to change notification settings - Fork 267
/
deque.py
60 lines (44 loc) · 1.35 KB
/
deque.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
class Deque:
def __init__(self):
self.items = []
def is_empty(self):
return len(self.items) == 0
def size(self):
return len(self.items)
def add_front(self, item):
self.items.insert(0, item)
def add_rear(self, item):
self.items.append(item)
def remove_front(self):
if not self.is_empty():
return self.items.pop(0)
else:
raise IndexError("Deque is empty")
def remove_rear(self):
if not self.is_empty():
return self.items.pop()
else:
raise IndexError("Deque is empty")
def peek_front(self):
if not self.is_empty():
return self.items[0]
else:
raise IndexError("Deque is empty")
def peek_rear(self):
if not self.is_empty():
return self.items[-1]
else:
raise IndexError("Deque is empty")
def __str__(self):
return str(self.items)
if __name__ == "__main__":
my_deque = Deque()
my_deque.add_front(1)
my_deque.add_rear(2)
my_deque.add_front(3)
print(my_deque) # Output: [3, 1, 2]
print(my_deque.remove_front()) # Output: 3
print(my_deque.remove_rear()) # Output: 2
print(my_deque.peek_front()) # Output: 1
print(my_deque.peek_rear()) # Output: 1
print(my_deque.size()) # Output: 1