Implement the basic algorithm in Python to deepen your understanding of the algorithm. The 18th bullet deals with stacks and queues. This time, it is a category of sorting, but it should be mentioned that stacks and queues are learned for comparison with the next sorting (heapsort), and are not sorting algorithms.
In the list where data is stored, extract from the end (the last one entered). Stack means to stack, as the name implies. The figure of the image in the cargo and the image in the list is shown below.
In the list where data is stored, extract from the beginning (the one entered first). Queue means "column", and as the name suggests, the image is that what you put in comes out from the opposite side. As before, the image of the cargo and the image of the list are shown below. In addition, as shown in the figure, in the queue, data storage and retrieval are named enqueue and dequeue.
The stack code and its output are shown below.
stack.py
"""
2021/01/12
@Yuya Shimizu
stack(stack)
"""
List = []
List.append(3) #on stack[3]Add
List.append(5) #on stack[5]Add
List.append(2) #on stack[2]Add
print(List)
temp = List.pop() #Take out from stack
print(f"\n take out: {temp}\n")
print(List)
temp = List.pop() #Take out from stack
print(f"\n take out: {temp}\n")
print(List)
List.append(4) #on stack[4]Add
print(f"\n added: 4\n")
print(List)
temp = List.pop() #Take out from stack
print(f"\n take out: {temp}\n")
print(List)
[3, 5, 2]
take out: 2
[3, 5]
take out: 5
[3]
add to: 4
[3, 4]
take out: 4
[3]
The queue code and its output are shown below.
queue_program.py
"""
2021/01/12
@Yuya Shimizu
queue(queue)
"""
import queue
q = queue.Queue()
q.put(3) #In the queue[3]Add
q.put(5) #In the queue[5]Add
q.put(2) #In the queue[2]Add
print(q.queue)
temp = q.get() #Remove from queue
print(f"\n Decue: {temp}\n")
print(q.queue)
temp = q.get() #Remove from queue
print(f"\n Decue: {temp}\n")
print(q.queue)
q.put(4) #In the queue[4]Add
print(f"\n enqueue: 4\n")
print(q.queue)
temp = q.get() #Remove from queue
print(f"\n Decue: {temp}\n")
print(q.queue)
deque([3, 5, 2])
Decue: 3
deque([5, 2])
Decue: 5
deque([2])
Enqueue: 4
deque([2, 4])
Decue: 2
deque([4])
Regarding queues, Python has a module called queue, and by using the Queue class, you can implement the put method, that is, the enqueue, and the get method, that is, the dequeue. Note that the queue module cannot be loaded with the name queue.py
.
This time I learned about stacks and cues. I didn't learn to sort directly, but I learned about a new queue for handling data. Also, in the stack, I handle pop ()
again, and I feel familiar with how to use pop ()
. I am looking forward to learning a better method than what I learned this time in the next heapsort.
Introduction to algorithms starting with Python: Standards and computational complexity learned with traditional algorithms Written by Toshikatsu Masui, Shoeisha
Recommended Posts