I wrote the stack in Python

What is a stack in the first place? Yes, store and retrieve data. That's all. However, I want to be able to retrieve the last stored data first. Σ(oдΟ;)

For example, as shown below, while stacking 6 data vertically Suppose you have a box that you can store. 図1.PNG

First, empty the box, store A, and then remove it. 図2.PNG After storing and retrieving A, it returned to its original empty state. It's easy.

Now, after naming the data storage as Push and the retrieval as Pop, I tried to figure out the movement of Push / Pop of the data a little more. I pushed A and B, and finally popped. The last thing left in the box is A, isn't it? 図3.PNG In this way, you can now imagine the behavior of the stack that pops the last Pushed data first.

I wish I didn't have to have a box depth of 6 !? I don't care about the details (laughs). Now let's write in Python.

Before that, if you don't understand the description here, We recommend studying with Progate !! https://prog-8.com/

Let's first prepare a box to realize the stack. The image looks like this. 図4.PNG I prepared a box named str and set the capacity as how many data can be stored. ptr represents the position from 1 to 6. I added the movement of ptr to the previous figure. 図5.PNG Like this, ptr (pointer) shows the position of the box that can be pushed. Now that you have an image of ptr, it's finally Python. I made a box.

stack.py


    def __init__(self,capacity:int = 10):
        self.str  = [None] * capacity
        self.capa = capacity
        self.ptr  = 0

"def __ init __" Determine the initial value in the prepared program! It is a cliché. The story doesn't start unless you load it first when the program runs. Next is Push.

stack.py


    def push(self,value):
        if self.ptr >= self.capa:
            raise top.full
        self.str[self.ptr] = value 
        print(self.str[self.ptr])
        self.ptr += 1

There is a print in between, but you can ignore it. The important thing is to first make sure that the ptr position is not Full. Full if ptr == capacity If ptr> capacity, the program is out of control !! You can see that we are checking with if self.ptr> = self.capa :. If it is not Full, set self.str [self.ptr] = value and Push is completed successfully. Increment ptr by one in preparation for the next Push. That's all we're doing with Push.

Next is Pop.

stack.py


    def pop(self):
        if self.ptr <= 0:
            raise top.empty
        self.ptr -= 1
        return self.str[self.ptr]

If the pointer ptr was negative, Because you will penetrate the bottom and screw the data into the ground For the time being, check with the if statement. I'm sure some of you may have wondered here. As a side note, in the Python world, storage doesn't start at 1. It starts from 0. I'm sorry the first figure wasn't good. 図9.PNG So if ptr = 0, it means empty. It's Empty. If it is not empty, decrement ptr by 1 as shown below. Specify the data to retrieve. 図10.PNG After that, you can retrieve the stored data by doing return self.str [self.ptr].

No, I was able to return the data with return, The specified area is not empty! ?? Yes! That's right !! Bakon! (----) / ☆ (* _ *)

Actually, the stack manages the data at the position of ptr. Even if you haven't emptied it, the next Push will automatically rewrite it, right? That's why you can stack by just looking at the movement of ptr. That's why I will put the whole picture of the stack prepared in a hurry.

stack.py


class top:
    class full(Exception):
        pass
    class empty(Exception):
        pass    
    
    def __init__(self,capacity:int = 10):
        self.str  = [None] * capacity
        self.capa = capacity
        self.ptr  = 0
        
    def push(self,value):
        if self.ptr >= self.capa:
            raise top.full
        self.str[self.ptr] = value 
        print(self.str[self.ptr])
        self.ptr += 1
        
    def pop(self):
        if self.ptr <= 0:
            raise top.empty
        self.ptr -= 1
        return self.str[self.ptr]

test = top()

while True:
    num = int(input("select 1.push , 2.pop : "))
    
    if num == 1 :
        s = int(input("enter data: "))
        try:
            test.push(s)
        except test.full:
            print("full!")
    elif num == 2:
        try:
            x = test.pop()
            print(x)
        except test.empty:
            print("empty!")
    else:
        break

Maybe "__ init __", push, pop is the key, so if you know that, I hope you understand.

This is my first post, so if there is something missing or difficult to understand Please kindly point out !! m (_ _) m

Other articles
Try implementing two stacks in one array in Python
Minimum value for stack made with Python(min)Add the ability to return but push/pop/min is basic O(1) !!

Recommended Posts

I wrote the stack in Python
I wrote the queue in Python
I wrote python in Japanese
I wrote Fizz Buzz in Python
[Python beginner] I collected the articles I wrote
I wrote the sliding wing in creation.
I wrote the code to write the code of Brainf * ck in python
A memo that I wrote a quicksort in Python
I tried simulating the "birthday paradox" in Python
I tried the least squares method in Python
I wrote a class in Python3 and Java
I wrote "Introduction to Effect Verification" in Python
I wrote the hexagonal architecture in go language
I implemented the inverse gamma function in python
I want to display the progress in Python!
Download the file in Python
Find the difference in Python
Stack and Queue in Python
I understand Python in Japanese!
What I learned in Python
I downloaded the python source
I tried to graph the packages installed in Python
I want to write in Python! (3) Utilize the mock
I want to use the R dataset in python
[Fundamental Information Technology Engineer Examination] I wrote the algorithm of Euclidean algorithm in Python.
Note that I understand the least squares algorithm. And I wrote it in Python.
Python in the browser: Brython's recommendation
Save the binary file in Python
Hit the Sesami API in Python
Get the desktop path in Python
I wrote the basic grammar of Python with Jupyter Lab
I wrote the basic operation of Seaborn in Jupyter Lab
I participated in the ISUCON10 qualifying!
Get the script path in Python
In the python command python points to python3.8
Implement the Singleton pattern in Python
I tried programming the chi-square test in Python and Java.
I wrote Gray Scale in Pytorch
I wrote it in Go to understand the SOLID principle
Hit the web API in Python
I liked the tweet with python. ..
I just wrote the original material for the python sample code
I learned about processes in Python
I can't install scikit-learn in Python
I tried to implement the mail sending function in Python
Examine the object's class in python
I wrote the basic operation of Numpy in Jupyter Lab.
Get the desktop path in Python
Get the host name in Python
Access the Twitter API in Python
Depth-first search using stack in Python
I wrote a script that splits the image in two
Master the weakref module in Python
I wrote a doctest in "I tried to simulate the probability of a bingo game with Python"
I compared the calculation time of the moving average written in Python
Movement that changes direction in the coordinate system I tried Python 3
[Python] I wrote the route of the typhoon on the map using folium
I got an AttributeError when mocking the open method in python
I wrote a function to load a Git extension script in Python
I wrote a script to extract a web page link in Python
I put Python 2.7 in Sakura VPS 1GB.