Skip to content

Commit 80a885c

Browse files
limbad-YKcclauss
andauthored
Update pop function (#5544)
* Updated Pop function Added underflow condition * Update Pop Function Added condition to check underflow of stack * Update stack.py * if not self.stack: raise StackUnderflowError * Add doctests * StackUnderflowError * ..., not .... * Update stack.py Co-authored-by: Christian Clauss <[email protected]>
1 parent b72a66b commit 80a885c

File tree

1 file changed

+30
-8
lines changed

1 file changed

+30
-8
lines changed

data_structures/stacks/stack.py

+30-8
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,10 @@ class StackOverflowError(BaseException):
55
pass
66

77

8+
class StackUnderflowError(BaseException):
9+
pass
10+
11+
812
class Stack:
913
"""A stack is an abstract data type that serves as a collection of
1014
elements with two principal operations: push() and pop(). push() adds an
@@ -31,11 +35,29 @@ def push(self, data):
3135
self.stack.append(data)
3236

3337
def pop(self):
34-
"""Pop an element off of the top of the stack."""
38+
"""
39+
Pop an element off of the top of the stack.
40+
41+
>>> Stack().pop()
42+
Traceback (most recent call last):
43+
...
44+
data_structures.stacks.stack.StackUnderflowError
45+
"""
46+
if not self.stack:
47+
raise StackUnderflowError
3548
return self.stack.pop()
3649

3750
def peek(self):
38-
"""Peek at the top-most element of the stack."""
51+
"""
52+
Peek at the top-most element of the stack.
53+
54+
>>> Stack().pop()
55+
Traceback (most recent call last):
56+
...
57+
data_structures.stacks.stack.StackUnderflowError
58+
"""
59+
if not self.stack:
60+
raise StackUnderflowError
3961
return self.stack[-1]
4062

4163
def is_empty(self) -> bool:
@@ -67,22 +89,22 @@ def test_stack() -> None:
6789
try:
6890
_ = stack.pop()
6991
assert False # This should not happen
70-
except IndexError:
92+
except StackUnderflowError:
7193
assert True # This should happen
7294

7395
try:
7496
_ = stack.peek()
7597
assert False # This should not happen
76-
except IndexError:
98+
except StackUnderflowError:
7799
assert True # This should happen
78100

79101
for i in range(10):
80102
assert stack.size() == i
81103
stack.push(i)
82104

83-
assert bool(stack) is True
84-
assert stack.is_empty() is False
85-
assert stack.is_full() is True
105+
assert bool(stack)
106+
assert not stack.is_empty()
107+
assert stack.is_full()
86108
assert str(stack) == str(list(range(10)))
87109
assert stack.pop() == 9
88110
assert stack.peek() == 8
@@ -96,7 +118,7 @@ def test_stack() -> None:
96118
except StackOverflowError:
97119
assert True # This should happen
98120

99-
assert stack.is_empty() is False
121+
assert not stack.is_empty()
100122
assert stack.size() == 10
101123

102124
assert 5 in stack

0 commit comments

Comments
 (0)