Add a function to return the minimum value (min) to the stack made with Python, but push / pop / min is basic O (1) !!

Good evening everyone By saying my article is also total 400 view As far as I am happy, thank you m (_ _) m If it's hard to understand, you can comment (o ゚ o) no YO--

The challenge of using my summer vacation was also meaningful I'm sick. Summer vacation is over today I will be working from next week. Tomorrow and the day after tomorrow will be training for childcare and housework (laughs)

Find time if you can I would like to continue this activity, so please support me.

By the way, O (1) !? I don't know what to explain from there I will omit it because it will be bald (laugh)

If you look at the article by an expert, the point is for single item or for nesting or while + if. I felt like it would be O (1) if I quit (I wonder if it's okay to put the URL on my own. https://qiita.com/drken/items/872ebc3a2b5caaa4a0d0

The other day, I made a stack with the following idea, https://qiita.com/AKpirion/items/f3d5b51ab2ee9080e9c6 For the time being, push / pop seems to have no problem in understanding O (1) as a description.

Now, for the implementation of min, when you run the min function, it is essential to use the for statement to find the minimum value from the stacked data. So, in order to satisfy O (1), I thought it would be good if I could update the box that stores the minimum value every time I push. Therefore, I added str_min to the initial value.

stack_min.py


class top:
    def __init__(self, capacity: int = 5):
        self.str = [None] * capacity
        self.capa = capacity
        self.ptr = 0
        self.str_min = float("inf") #Box to store the minimum value

The reason why self.str_min is set to float ("inf"), that is, infinity, is This is because the first pushed value can always be stored in str_min.

stack_min.py


    def min_str(self, value):
        #self.str_min = min(self.str_min,value)
        if self.str_min > value: #Input value value is str_If it is smaller than min, str_update min
            self.str_min = value #self.str_min <If it is value, do nothing and return
        return self.str_min

Personally, I think you can do it with min () as shown in the comment just below def .. in the above figure. I wasn't confident when I was told O (1) !?, so I ran away with an if statement. Is there any way to check this !? I don't have time for the time being, so I'll go to Push.

stack_min.py


    def push(self, value):
        if self.ptr >= self.capa:
            raise top.full
        self.str[self.ptr] = value  #Push data to str!
        top.min_str(self, value)    #Pushed data and str_Compare with min and update minimum value
        self.ptr += 1

The description of Push is basically the same as before, By inserting top.min_str (self, value), the minimum value can be updated every time Push is performed. It was good, it seems that the trouble of searching can be simplified (*'艸 `)

And the last time you call min I needed a little ingenuity. For now, take a look at the code below.

stack_min.py


while True:
    num = int(input("select 1.push , 2.pop : , 3.min "))

    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!")
    elif num == 3:
        print(test.min_str(float("inf"))) #Compare infinity and minimum
    else:
        break

I can call min by typing 3 first, Since it is def min_str (self, value) If you don't put something in the value part, you will get an error. So I pushed infinity to make sure I could get the minimum value.

This time, there were no pictures with images, I'm sorry. I also wrote an article like this, so please do not hesitate to contact me.

Try implementing two stacks in one array in Python https://qiita.com/AKpirion/items/2e74eecd30063a01d2fc

Have a nice weekend ・ ω ・ ´) 尸

Recommended Posts

Add a function to return the minimum value (min) to the stack made with Python, but push / pop / min is basic O (1) !!
Add a function to tell the weather of today to slack bot (made by python)
[Introduction to Python] How to split a character string with the split function
[Python] What is a formal argument? How to set the initial value
[Python] Explains how to use the range function with a concrete example
[Introduction to Python] How to write a character string with the format function
I made a function to see the movement of a two-dimensional array (Python)
[Python] Make sure the received function is a user-defined function
[Linux] [C / C ++] How to get the return address value of a function and the function name of the caller
[C / C ++] Pass the value calculated in C / C ++ to a python function to execute the process, and use that value in C / C ++.
The value of meta when specifying a function with no return value in Dask dataframe apply
I made a class to get the analysis result by MeCab in ndarray with python
I made a function to crop the image of python openCV, so please use it.
I also tried to imitate the function monad and State monad with a generator in Python
I want to initialize if the value is empty (python)
Create a Mastodon bot with a function to automatically reply with Python
Minimum knowledge to get started with the Python logging module
I made a package to filter time series with python
Probably the easiest way to create a pdf with Python3
I made a function to check the model of DCGAN
To return char * in a callback function using ctypes in Python
How to get the last (last) value in a list in Python
The usual way to add a Kernel with Jupyter Notebook
[Python] The first step to making a game with Pyxel
[Introduction to Python] How to get data with the listdir function
Extract the value closest to a value from a Python list element
In the python dictionary, if a non-existent key is accessed, initialize it with an arbitrary value
I made a function to check if the webhook is received in Lambda for the time being
A simple reason why the return value of round (2.675,2) is 2.67 in python (it should be 2.68 in reality ...)