-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathstacks.py
69 lines (55 loc) · 1.57 KB
/
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
# Python implementations of stacks - List-based implementation and Deque-based implementation
class ListBasedStack:
def __init__(self):
self.stack = []
def push(self, item):
self.stack.append(item)
def pop(self):
if not self.is_empty():
return self.stack.pop()
raise IndexError("pop from empty stack")
def peek(self):
if not self.is_empty():
return self.stack[-1]
raise IndexError("peek from empty stack")
def is_empty(self):
return len(self.stack) == 0
from collections import deque
class DequeBasedStack:
def __init__(self):
self.stack = deque()
def push(self, item):
self.stack.append(item)
def pop(self):
if not self.is_empty():
return self.stack.pop()
raise IndexError("pop from empty stack")
def peek(self):
if not self.is_empty():
return self.stack[-1]
raise IndexError("peek from empty stack")
def is_empty(self):
return len(self.stack) == 0
# Test cases
stack = ListBasedStack()
stack.push(1)
stack.push(2)
stack.push(3)
assert stack.peek() == 3
assert stack.pop() == 3
assert stack.peek() == 2
assert stack.pop() == 2
assert stack.peek() == 1
assert stack.pop() == 1
assert stack.is_empty() == True
stack = DequeBasedStack()
stack.push(1)
stack.push(2)
stack.push(3)
assert stack.peek() == 3
assert stack.pop() == 3
assert stack.peek() == 2
assert stack.pop() == 2
assert stack.peek() == 1
assert stack.pop() == 1
assert stack.is_empty() == True