diff --git a/README.md b/README.md index d8bc2185..46b10648 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ This repository contains examples of various algorithms written on different pro | Data Structure | C | CPP | Java | Python | |:----------------------------------------------------------------------------------------------- |:-------------------------------------:|:-------------------------------------:|:-------------------------------------:|:-------------------------------------:| | [Queue](https://en.wikipedia.org/wiki/Queue_(abstract_data_type)) | | [:octocat:](queue/Cpp) | | | -| [Stack](https://en.wikipedia.org/wiki/Stack_(abstract_data_type)) | | | [:octocat:](stack/Java) | | +| [Stack](https://en.wikipedia.org/wiki/Stack_(abstract_data_type)) | | | [:octocat:](stack/Java) | [:octocat:](stack/Python) | | [Linear Linked List](https://en.wikipedia.org/wiki/Linked_list) | [:octocat:](linked_list/C) | | | | | [AVL Tree](https://en.wikipedia.org/wiki/AVL_tree) | | | [:octocat:](avl_tree/Java) | | diff --git a/stack/Python/stack.py b/stack/Python/stack.py new file mode 100644 index 00000000..8ae7ecf8 --- /dev/null +++ b/stack/Python/stack.py @@ -0,0 +1,63 @@ +class Stack: + """ + Class for operations related to stack. + """ + + def __init__(self): + + self.stack = [] # Initialise empty stack + + def push(self, dataval): + """ + Method to push items in stack. + + :param dataval: Value that user needs to push. + """ + + self.stack.append(dataval) + + def pop(self): + """ + Method for removing the last element from the stack. + + :return: Element that is popped. + """ + + if len(self.stack) <= 0: + # Raise an error if stack is empty. + return "No element in the Stack" + + else: + return self.stack.pop() + + def top(self): + """ + Method to show the last element of the stack. + + :return: last element of the stack. + """ + + return self.stack[len(self.stack)-1] + + def display(self): + """ + Method to print all elements of the stack. + """ + + print(*self.stack) + + +def main(): + AStack = Stack() + AStack.push("Mon") + AStack.push("Tue") + AStack.pop() + AStack.push("Wed") + m = AStack.top() + print(m) + AStack.push("Thu") + AStack.display() + + +if __name__ == "__main__": + main()