I wrote the queue in Python

Good evening Continue to receive various advice from everyone Two weeks are about to pass.

Thank you so much. m (_ _) m

First, prepare a stack, modify it and bring it to the queue I will take an approach.

stack.py


class Stack:
    class full(Exception):
        pass
    def __init__(self,size):
        #Stack body
        self.str = []
        #Specify the number of data that can be stacked
        self.size = size
    def push(self,value):
        #Stack body>Exception handling for the specified number of data
        if len(self.str) >= self.size:
            raise Stack.full
        #Push if there is no problem
        self.str.append(value)
    def pop(self):
        print(self.str.pop())
    def view(self):
        print(self.str)

x = int(input("stack size is "))
test = Stack(x)  
    
while True:
    num = int(input("1.push 2.pop: "))

    if num == 1:
        x = int(input("push data is "))
        try:#Normal processing
            test.push(x)
            test.view()
        except:#Exception handling
            print("Full!")
    elif num == 2:
        try:#Normal processing
            test.pop()
            test.view()
        except:#Exception handling
            print("Empty!")
    else:
        break

No, it's a description I couldn't think of two weeks ago (; ´ ・ ω ・) Now, how do you get it to the queue from here? What was the difference between a stack and a queue in the first place? .. Basically, the movement of pop is different. 図1.PNG As shown in the figure, in the case of a queue, the data saved first is taken out. If you do push / pop randomly, the contents will be messed up, so I don't know where the first data is.

There is a concept of ring buffer as a countermeasure, Queues are realized by managing where is the first. .. .. I'm using python Isn't it easy? ?? ??

So, first, let's review the nature of pop.

test.py


num = [3,2,1]

for i in range(3):
    print(f"num[{i}] = {num[i]}")

##Execution result##
#num[0] = 3#
#num[1] = 2#
#num[2] = 1#
############

Let's put pop in. I want to queue, so I set it to pop (0) Let's retrieve the First data.

test.py


num = [3,2,1]
num.pop(0)
for i in range(2):
    print(f"num[{i}] = {num[i]}")

##Execution result##
#num[0] = 2#
#num[1] = 1#
############

[Wall] * ゚) Hmm? Pop the first num [0], that is, take it out, As a result of the deletion, the remaining elements are left-justified.

That's right, the elements that remain after deleting the beginning are It will also be relocated from 0. What, if you do it yourself, you don't need a ring buffer !?

Queues are basically the same as stacks, fetching data, You only need to write once per address. Therefore, pop () defined in the above stack, the description to be extracted from the end If you change to pop (0), the description that is always taken out from the beginning, it will be a queue.

Queue??.py


class Stack:
    class full(Exception):
        pass
    def __init__(self,size):
        self.str = []
        self.size = size
    def push(self,value):
        if len(self.str) >= self.size:
            raise Stack.full
        self.str.append(value)
    def pop(self):
        print(self.str.pop(0)) #Change only here!!Change before) pop()After change) pop(0)
    def view(self):
        print(self.str)

x = int(input("stack size is "))
test = Stack(x)  
    
while True:
    num = int(input("1.push 2.pop: "))

    if num == 1:
        x = int(input("push data is "))
        try:
            test.push(x)
            test.view()
        except:
            print("Full!")
    elif num == 2:
        try:
            test.pop()
            test.view()
        except:
            print("Empty!")
    else:
        break

Below are the execution results.

push data is 4 #Push 4
[1, 2, 3, 4]   #Memory contents after push

1.push 2.pop: 2#2.Select pop
1              #str[0]Pop the 1 stored in
[2, 3, 4]      #Memory contents after pop

1.push 2.pop: 2#2.Select pop
2              #str[0]Pop the 1 stored in
[3, 4]         #Memory contents after pop

1.push 2.pop: 2
3
[4]

1.push 2.pop: 2
4
[]

1.push 2.pop: 2
Empty!

With this kind of feeling, I was able to easily realize the cue. Hmmm, but make a link buffer properly and explain I feel that it is better for me to put it on. Alright, let's do it! !! Someday. ..

Recommended Posts

I wrote the queue in Python
I wrote the stack in Python
I wrote python in Japanese
I wrote Fizz Buzz in Python
I wrote the selection sort in C
[Python beginner] I collected the articles I wrote
I wrote the sliding wing in creation.
Queue processing in Python
I wrote the code to write the code of Brainf * ck in python
A memo that I wrote a quicksort in Python
I tried the least squares method in Python
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 implemented breadth-first search in python (queue, drawing self-made)
I tried to graph the packages installed in Python
I want to use the R dataset in python
Note that I understand the least squares algorithm. And I wrote it in Python.
I checked the Python package pre-installed in Google Cloud Dataflow
Getting the arXiv API in Python
I tried the accuracy of three Stirling's approximations in python
I got lost in the maze
Python in the browser: Brython's recommendation
Save the binary file in Python
Hit the Sesami API in Python
I wrote the basic grammar of Python with Jupyter Lab
I participated in the ISUCON10 qualifying!
In the python command python points to python3.8
Implement the Singleton pattern in Python
The story that `while queue` did not work in python
I tried programming the chi-square test in Python and Java.
I wrote an empty directory automatic creation script in Python
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 can't install scikit-learn in Python
I tried to implement the mail sending function in Python
Calculate the previous month 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
I tried Line notification in Python
The first step in Python Matplotlib
I wrote a script that splits the image in two
Master the weakref module in Python
Is the priority queue heapq in Competitive Pro (Python)? queue.PriorityQueue? Which one should I use?
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
I got an AttributeError when mocking the open method in python