From b6fcee311430d1bcf81253898b08f9e80d20064d Mon Sep 17 00:00:00 2001 From: Akash Date: Sun, 3 May 2020 19:45:31 +0530 Subject: [PATCH] Check if a item exist in stack or not (#1931) * Check if a item exist in stack or not * implemented __contains__ method in stack * made changes in __contains__ --- data_structures/stacks/stack.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/data_structures/stacks/stack.py b/data_structures/stacks/stack.py index 53a40a7b7..a96275aa8 100644 --- a/data_structures/stacks/stack.py +++ b/data_structures/stacks/stack.py @@ -46,7 +46,11 @@ class Stack: def size(self): """ Return the size of the stack.""" return len(self.stack) - + + def __contains__(self, item) -> bool: + """Check if item is in stack""" + return item in self.stack + class StackOverflowError(BaseException): pass @@ -66,3 +70,7 @@ if __name__ == "__main__": 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") +