Updated Stack (#2414)

* * Added type hints
* Added test
* Formated code

* updating DIRECTORY.md

* Update stack.py

* Test error conditions for pop, peek, and

Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
Co-authored-by: Christian Clauss <cclauss@me.com>
This commit is contained in:
Du Yuanchao 2020-09-13 19:56:03 +08:00 committed by GitHub
parent d6bff5c133
commit 44b8cb0c81
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 79 additions and 32 deletions

View File

@ -24,6 +24,9 @@
* [Sudoku](https://github.com/TheAlgorithms/Python/blob/master/backtracking/sudoku.py) * [Sudoku](https://github.com/TheAlgorithms/Python/blob/master/backtracking/sudoku.py)
* [Sum Of Subsets](https://github.com/TheAlgorithms/Python/blob/master/backtracking/sum_of_subsets.py) * [Sum Of Subsets](https://github.com/TheAlgorithms/Python/blob/master/backtracking/sum_of_subsets.py)
## Bit Manipulation
* [Binary Or Operator](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_or_operator.py)
## Blockchain ## Blockchain
* [Chinese Remainder Theorem](https://github.com/TheAlgorithms/Python/blob/master/blockchain/chinese_remainder_theorem.py) * [Chinese Remainder Theorem](https://github.com/TheAlgorithms/Python/blob/master/blockchain/chinese_remainder_theorem.py)
* [Diophantine Equation](https://github.com/TheAlgorithms/Python/blob/master/blockchain/diophantine_equation.py) * [Diophantine Equation](https://github.com/TheAlgorithms/Python/blob/master/blockchain/diophantine_equation.py)
@ -50,6 +53,7 @@
* [Deterministic Miller Rabin](https://github.com/TheAlgorithms/Python/blob/master/ciphers/deterministic_miller_rabin.py) * [Deterministic Miller Rabin](https://github.com/TheAlgorithms/Python/blob/master/ciphers/deterministic_miller_rabin.py)
* [Diffie](https://github.com/TheAlgorithms/Python/blob/master/ciphers/diffie.py) * [Diffie](https://github.com/TheAlgorithms/Python/blob/master/ciphers/diffie.py)
* [Elgamal Key Generator](https://github.com/TheAlgorithms/Python/blob/master/ciphers/elgamal_key_generator.py) * [Elgamal Key Generator](https://github.com/TheAlgorithms/Python/blob/master/ciphers/elgamal_key_generator.py)
* [Enigma Machine2](https://github.com/TheAlgorithms/Python/blob/master/ciphers/enigma_machine2.py)
* [Hill Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/hill_cipher.py) * [Hill Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/hill_cipher.py)
* [Mixed Keyword Cypher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/mixed_keyword_cypher.py) * [Mixed Keyword Cypher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/mixed_keyword_cypher.py)
* [Morse Code Implementation](https://github.com/TheAlgorithms/Python/blob/master/ciphers/morse_code_implementation.py) * [Morse Code Implementation](https://github.com/TheAlgorithms/Python/blob/master/ciphers/morse_code_implementation.py)
@ -105,6 +109,7 @@
* [Segment Tree Other](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/segment_tree_other.py) * [Segment Tree Other](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/segment_tree_other.py)
* [Treap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/treap.py) * [Treap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/treap.py)
* Disjoint Set * Disjoint Set
* [Alternate Disjoint Set](https://github.com/TheAlgorithms/Python/blob/master/data_structures/disjoint_set/alternate_disjoint_set.py)
* [Disjoint Set](https://github.com/TheAlgorithms/Python/blob/master/data_structures/disjoint_set/disjoint_set.py) * [Disjoint Set](https://github.com/TheAlgorithms/Python/blob/master/data_structures/disjoint_set/disjoint_set.py)
* Hashing * Hashing
* [Double Hash](https://github.com/TheAlgorithms/Python/blob/master/data_structures/hashing/double_hash.py) * [Double Hash](https://github.com/TheAlgorithms/Python/blob/master/data_structures/hashing/double_hash.py)
@ -419,6 +424,7 @@
* [Sum Of Geometric Progression](https://github.com/TheAlgorithms/Python/blob/master/maths/sum_of_geometric_progression.py) * [Sum Of Geometric Progression](https://github.com/TheAlgorithms/Python/blob/master/maths/sum_of_geometric_progression.py)
* [Test Prime Check](https://github.com/TheAlgorithms/Python/blob/master/maths/test_prime_check.py) * [Test Prime Check](https://github.com/TheAlgorithms/Python/blob/master/maths/test_prime_check.py)
* [Trapezoidal Rule](https://github.com/TheAlgorithms/Python/blob/master/maths/trapezoidal_rule.py) * [Trapezoidal Rule](https://github.com/TheAlgorithms/Python/blob/master/maths/trapezoidal_rule.py)
* [Ugly Numbers](https://github.com/TheAlgorithms/Python/blob/master/maths/ugly_numbers.py)
* [Volume](https://github.com/TheAlgorithms/Python/blob/master/maths/volume.py) * [Volume](https://github.com/TheAlgorithms/Python/blob/master/maths/volume.py)
* [Zellers Congruence](https://github.com/TheAlgorithms/Python/blob/master/maths/zellers_congruence.py) * [Zellers Congruence](https://github.com/TheAlgorithms/Python/blob/master/maths/zellers_congruence.py)
@ -474,6 +480,7 @@
* [Sdes](https://github.com/TheAlgorithms/Python/blob/master/other/sdes.py) * [Sdes](https://github.com/TheAlgorithms/Python/blob/master/other/sdes.py)
* [Sierpinski Triangle](https://github.com/TheAlgorithms/Python/blob/master/other/sierpinski_triangle.py) * [Sierpinski Triangle](https://github.com/TheAlgorithms/Python/blob/master/other/sierpinski_triangle.py)
* [Tower Of Hanoi](https://github.com/TheAlgorithms/Python/blob/master/other/tower_of_hanoi.py) * [Tower Of Hanoi](https://github.com/TheAlgorithms/Python/blob/master/other/tower_of_hanoi.py)
* [Triplet Sum](https://github.com/TheAlgorithms/Python/blob/master/other/triplet_sum.py)
* [Two Sum](https://github.com/TheAlgorithms/Python/blob/master/other/two_sum.py) * [Two Sum](https://github.com/TheAlgorithms/Python/blob/master/other/two_sum.py)
* [Word Patterns](https://github.com/TheAlgorithms/Python/blob/master/other/word_patterns.py) * [Word Patterns](https://github.com/TheAlgorithms/Python/blob/master/other/word_patterns.py)
@ -600,6 +607,12 @@
* [Solution42](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_42/solution42.py) * [Solution42](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_42/solution42.py)
* Problem 43 * Problem 43
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_43/sol1.py) * [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_43/sol1.py)
* Problem 44
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_44/sol1.py)
* Problem 45
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_45/sol1.py)
* Problem 46
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_46/sol1.py)
* Problem 47 * Problem 47
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_47/sol1.py) * [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_47/sol1.py)
* Problem 48 * Problem 48
@ -608,10 +621,14 @@
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_52/sol1.py) * [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_52/sol1.py)
* Problem 53 * Problem 53
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_53/sol1.py) * [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_53/sol1.py)
* Problem 55
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_55/sol1.py)
* Problem 551 * Problem 551
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_551/sol1.py) * [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_551/sol1.py)
* Problem 56 * Problem 56
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_56/sol1.py) * [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_56/sol1.py)
* Problem 63
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_63/sol1.py)
* Problem 67 * Problem 67
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_67/sol1.py) * [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_67/sol1.py)
* Problem 76 * Problem 76
@ -673,7 +690,6 @@
* [Recursive Insertion Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/recursive_insertion_sort.py) * [Recursive Insertion Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/recursive_insertion_sort.py)
* [Selection Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/selection_sort.py) * [Selection Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/selection_sort.py)
* [Shell Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/shell_sort.py) * [Shell Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/shell_sort.py)
* [Sleep Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/sleep_sort.py)
* [Stooge Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/stooge_sort.py) * [Stooge Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/stooge_sort.py)
* [Strand Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/strand_sort.py) * [Strand Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/strand_sort.py)
* [Tim Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/tim_sort.py) * [Tim Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/tim_sort.py)
@ -685,6 +701,7 @@
## Strings ## Strings
* [Aho-Corasick](https://github.com/TheAlgorithms/Python/blob/master/strings/aho-corasick.py) * [Aho-Corasick](https://github.com/TheAlgorithms/Python/blob/master/strings/aho-corasick.py)
* [Boyer Moore Search](https://github.com/TheAlgorithms/Python/blob/master/strings/boyer_moore_search.py) * [Boyer Moore Search](https://github.com/TheAlgorithms/Python/blob/master/strings/boyer_moore_search.py)
* [Capitalize](https://github.com/TheAlgorithms/Python/blob/master/strings/capitalize.py)
* [Check Anagrams](https://github.com/TheAlgorithms/Python/blob/master/strings/check_anagrams.py) * [Check Anagrams](https://github.com/TheAlgorithms/Python/blob/master/strings/check_anagrams.py)
* [Check Pangram](https://github.com/TheAlgorithms/Python/blob/master/strings/check_pangram.py) * [Check Pangram](https://github.com/TheAlgorithms/Python/blob/master/strings/check_pangram.py)
* [Is Palindrome](https://github.com/TheAlgorithms/Python/blob/master/strings/is_palindrome.py) * [Is Palindrome](https://github.com/TheAlgorithms/Python/blob/master/strings/is_palindrome.py)
@ -715,6 +732,7 @@
* [Emails From Url](https://github.com/TheAlgorithms/Python/blob/master/web_programming/emails_from_url.py) * [Emails From Url](https://github.com/TheAlgorithms/Python/blob/master/web_programming/emails_from_url.py)
* [Fetch Bbc News](https://github.com/TheAlgorithms/Python/blob/master/web_programming/fetch_bbc_news.py) * [Fetch Bbc News](https://github.com/TheAlgorithms/Python/blob/master/web_programming/fetch_bbc_news.py)
* [Fetch Github Info](https://github.com/TheAlgorithms/Python/blob/master/web_programming/fetch_github_info.py) * [Fetch Github Info](https://github.com/TheAlgorithms/Python/blob/master/web_programming/fetch_github_info.py)
* [Fetch Jobs](https://github.com/TheAlgorithms/Python/blob/master/web_programming/fetch_jobs.py)
* [Get Imdb Top 250 Movies Csv](https://github.com/TheAlgorithms/Python/blob/master/web_programming/get_imdb_top_250_movies_csv.py) * [Get Imdb Top 250 Movies Csv](https://github.com/TheAlgorithms/Python/blob/master/web_programming/get_imdb_top_250_movies_csv.py)
* [Get Imdbtop](https://github.com/TheAlgorithms/Python/blob/master/web_programming/get_imdbtop.py) * [Get Imdbtop](https://github.com/TheAlgorithms/Python/blob/master/web_programming/get_imdbtop.py)
* [Slack Message](https://github.com/TheAlgorithms/Python/blob/master/web_programming/slack_message.py) * [Slack Message](https://github.com/TheAlgorithms/Python/blob/master/web_programming/slack_message.py)

View File

@ -1,4 +1,5 @@
__author__ = "Omkar Pathak" class StackOverflowError(BaseException):
pass
class Stack: class Stack:
@ -7,18 +8,17 @@ class Stack:
element to the top of the stack, and pop() removes an element from the top element to the top of the stack, and pop() removes an element from the top
of a stack. The order in which elements come off of a stack are of a stack. The order in which elements come off of a stack are
Last In, First Out (LIFO). Last In, First Out (LIFO).
https://en.wikipedia.org/wiki/Stack_(abstract_data_type) https://en.wikipedia.org/wiki/Stack_(abstract_data_type)
""" """
def __init__(self, limit=10): def __init__(self, limit: int = 10):
self.stack = [] self.stack = []
self.limit = limit self.limit = limit
def __bool__(self): def __bool__(self) -> bool:
return bool(self.stack) return bool(self.stack)
def __str__(self): def __str__(self) -> str:
return str(self.stack) return str(self.stack)
def push(self, data): def push(self, data):
@ -29,21 +29,20 @@ class Stack:
def pop(self): def pop(self):
""" Pop an element off of the top of the stack.""" """ Pop an element off of the top of the stack."""
if self.stack: return self.stack.pop()
return self.stack.pop()
else:
raise IndexError("pop from an empty stack")
def peek(self): def peek(self):
""" Peek at the top-most element of the stack.""" """ Peek at the top-most element of the stack."""
if self.stack: return self.stack[-1]
return self.stack[-1]
def is_empty(self): def is_empty(self) -> bool:
""" Check if a stack is empty.""" """ Check if a stack is empty."""
return not bool(self.stack) return not bool(self.stack)
def size(self): def is_full(self) -> bool:
return self.size() == self.limit
def size(self) -> int:
""" Return the size of the stack.""" """ Return the size of the stack."""
return len(self.stack) return len(self.stack)
@ -52,24 +51,54 @@ class Stack:
return item in self.stack return item in self.stack
class StackOverflowError(BaseException): def test_stack() -> None:
pass """
>>> test_stack()
"""
stack = Stack(10)
assert bool(stack) is False
assert stack.is_empty() is True
assert stack.is_full() is False
assert str(stack) == "[]"
try:
_ = stack.pop()
assert False # This should not happen
except IndexError:
assert True # This should happen
try:
_ = stack.peek()
assert False # This should not happen
except IndexError:
assert True # This should happen
for i in range(10):
assert stack.size() == i
stack.push(i)
assert bool(stack) is True
assert stack.is_empty() is False
assert stack.is_full() is True
assert str(stack) == str(list(range(10)))
assert stack.pop() == 9
assert stack.peek() == 8
stack.push(100)
assert str(stack) == str([0, 1, 2, 3, 4, 5, 6, 7, 8, 100])
try:
stack.push(200)
assert False # This should not happen
except StackOverflowError:
assert True # This should happen
assert stack.is_empty() is False
assert stack.size() == 10
assert 5 in stack
assert 55 not in stack
if __name__ == "__main__": if __name__ == "__main__":
stack = Stack() test_stack()
for i in range(10):
stack.push(i)
print("Stack demonstration:\n")
print("Initial stack: " + str(stack))
print("pop(): " + str(stack.pop()))
print("After pop(), the stack is now: " + str(stack))
print("peek(): " + str(stack.peek()))
stack.push(100)
print("After push(100), the stack is now: " + str(stack))
print("is_empty(): " + str(stack.is_empty()))
print("size(): " + str(stack.size()))
num = 5
if num in stack:
print(f"{num} is in stack")