Stack and Queue in Python

This time, I read the Python tutorials from chapters 1 to 9 online, and it seemed that Stack and Queue could do something, so I wrote the code. Stack: Another name for Stack is LIFO (Last In First Out), but as the name suggests, it is the first data structure to be output when the last element is output. There are two functions required to implement a Stack: push (), which puts the element at the end of the Stack, and pop (), which puts the element from the end of the Stack. As an image, when stacking books, you should think that you will pick up from the top of the stacked books. The module looks like this and I will write the explanation later.

stack.py


class Stack:
    def __init__(self, stack = None):
        if type(stack) is type([]):
            self.stack = stack
        elif stack is None:
            self.stack = []
        else:
            print '\nError Message:\n\tYour input is not type of list!\n\tPlease enter list type!\n'
        
    def push(self, e):
        self.stack.append(e)    
        return self.stack       
        
    def pop(self):
        try:
            sEl = self.stack.pop()
            return (sEl, self.stack)  
        except IndexError:            
            print '\nError Message:\n\tThere is no element in the stack!\n'

First, I created a Stack class, and in the constructor, Stack takes a list as a parameter (argument). In Python, it seems to put self in the first parameter of the constructor for some reason, but when I look at the next line, it says self.stack. Maybe this is this in Java. I feel like I used this in Java to tell if the variable I want to access is defined locally or globally. (Maybe, absolutely, I forgot w) So in the case of Python, I think that it is possible to distinguish between the stack of parameter variable names and the stack of variables newly defined in this class. push(): Since the push of the first function only inserts the element at the end, just call append of the built-in function of the list by giving the e of the element taken by the parameter. Just in case, the stack is returned as a return value so that you can print how the Stack has changed. You should be able to see this with print when you call this function. pop(): Again, you can retrieve and remove the head element by simply using the built-in function pop (). Assign it to the new variable sEl (which stands for stackElement) and return it as a return value. In the return value, I wanted to return the stack itself to check if the stack configuration has changed, so I enclose it in tuples and return two values at the same time. If you call this function when the stack does not have any elements, IndexError will occur, so if an error occurs using try, the message after printing will be issued as a warning. try is used to execute the code inside and if there is a problem, catch it in the next block and issue a message. This is also used in Java for try & catch, so if you want to study Java from now on, please remember it.

Queue In Queue, when inserting an element, the same process as Stack is performed, but when ejecting an element, it is ejected from the first inserted element of the remaining elements. This is called FIFO (First In First Out). We will create two functions in the same way as Stack. First, I named the function to put in as enqueue () and the function to put out as dequeue (). As an image of this data structure, it may be easier to understand if you think that billiard balls are lined up in a row, pushed out at once from the end and dropped from the beginning into the hole.

queue.py


class Queue:
    def __init__(self, queue = None):
        if type(queue) is type([]):
            self.queue = queue
        elif queue is None:
            self.queue = []
        else:
            print '\nError Message:\n\tYour input is not type of list!\n\tPlease enter list type!\n'
        
    def enqueue(self, e):
        self.queue.append(e)   
        return self.queue     

    def dequeue(self):
        try:
            qEl = self.queue[0]     
            del self.queue[0]     
            return (qEl, self.queue)  
        except IndexError: 
            print '\nError Message:\n\tThere is no element in the queue!\n'

dequeue(): In enqueu (), I took the same procedure as push () of Stack, but in dequeue (), I want to retrieve the element that was put in first, so I assign the element in index 0 to a new variable and then delete it. .. By deleting with del, the element held by index 1 in the list will automatically move to index 0, so the oldest element in the list will be selected even when repeating. Here, like pop (), a try statement is used to indicate an error when the list does not have any elements, and a message is displayed in case of an error.

In this post, I implemented a simple data structure because I am almost a beginner in Python. I would like to read the Python reference book a little more and code an algorithm suitable for natural language processing etc., but I think that there are still many things I do not know what to do, so maybe I will create another data structure I may post it. After reading the reference book, if there are any interesting features of Python, I will post them all together. See you soon!

Note: The code in this post has only been a simple test and may not work. If you are using it yourself and have any problems, I will fix and edit it. If you use this code, or if you read it, please let us know in the comments or email if there is something missing or how to do it efficiently.

Recommended Posts

Stack and Queue in Python
Implementation module "deque" in queue and Python
Unittest and CI in Python
Algorithm learned with Python 18th: Sorting (stack and queue)
Difference between list () and [] in Python
Difference between == and is in python
Manipulate files and folders in Python
Assignments and changes in Python objects
Check and move directories in Python
Ciphertext in Python: IND-CCA2 and RSA-OAEP
Function synthesis and application in Python
I wrote the queue in Python
Export and output files in Python
Reverse Hiragana and Katakana in Python2.7
Reading and writing text in Python
[GUI in Python] PyQt5-Menu and Toolbar-
Depth-first search using stack in Python
I wrote the stack in Python
Create and read messagepacks in Python
Overlapping regular expressions in Python and Java
Quadtree in Python --2
Python in optimization
CURL in python
Differences in authenticity between Python and JavaScript
Metaprogramming in Python
Notes using cChardet and python3-chardet in Python 3.3.1.
Python 3.3 in Anaconda
Geocoding in python
SendKeys in Python
Ant book in python: Priority queue self-implementation
Modules and packages in Python are "namespaces"
Avoid nested loops in PHP and Python
Differences between Ruby and Python in scope
AM modulation and demodulation in Python Part 2
Meta-analysis in Python
difference between statements (statements) and expressions (expressions) in Python
Eigenvalues and eigenvectors: Linear algebra in Python <7>
Unittest in python
Line graphs and scale lines in python
Implement FIR filters in Python and C
Differences in syntax between Python and Java
Check and receive Serial port in Python (Port check)
Search and play YouTube videos in Python
Epoch in Python
Discord in Python
Sudoku in Python
DCI in Python
quicksort in python
Difference between append and + = in Python list
Difference between nonlocal and global in Python
Write O_SYNC file in C and Python
N-Gram in Python
Programming in python
Dealing with "years and months" in Python
Plink in Python
Constant in python
Read and write JSON files in Python
Easily graph data in shell and Python
Private methods and fields in python [encryption]
Find and check inverse matrix in Python
Lifegame in Python.