


Let's analyze Python queue-related applications and exercises together
This article brings you relevant knowledge about python, which mainly introduces queue-related application exercises, including how to use two stacks to implement a queue, and how to use two The queue implements a stack, determines the continuity of elements in the stack, etc. I hope it will be helpful to everyone.
Recommended learning: python tutorial
0. Learning objectives
We have learned the related concepts of queues and its implementation, and also learned about the wide application of queues in practical problems. The main purpose of this section is to further deepen the understanding of queues through queue-related exercises, and at the same time, be able to use queues to reduce the time complexity of solutions to some complex problems. .
1. Use two stacks to implement a queue
[Question] Given two stacks, implement a queue using only the basic operations of the stack.
[Ideas] The key to solving this problem lies in the reversal feature of the stack. A series of elements pushed onto the stack will be returned in the reverse order when popped off the stack. Therefore, using two stacks can achieve the return of elements in the same order (the reversed sequence of elements will be reversed again to get the original order). The specific operation is shown in the figure below:
[Algorithm]
Enqueue
enqueue
:
Push elements onto the stackstack_1
Dequeuedequeue
:
If the stackstack_2
is not empty:
stack_2
Pop the top element from the stack
Otherwise:
Pop all elements fromstack_1
and push them intostack_2
stack_2
Pop the top element from the stack
[code]
class Queue: def __init__(self): self.stack_1 = Stack() self.stack_2 = Stack() def enqueue(self, data): self.stack_1.push(data) def dequeue(self): if self.stack_2.isempty(): while not self.stack_1.isempty(): self.stack_2.push(self.stack_1.pop()) return self.stack_2.pop()
[Time and space complexity] The time complexity of entering the queue is O(1), if the stack stack_2
is not empty, then the time complexity of dequeuing is O( 1), if the stack stack_2
is empty, you need to remove the elements from stack_1
is transferred to stack_2
, but since the number of elements transferred in stack_2
is equal to the number of elements dequeued, the amortized time complexity of dequeuing is O(1) .
2. Implement a stack using two queues
[Question] Given two queues, implement a stack using only the basic operations of the queue.
[Idea] Since the queue does not have the feature of reversing the order, the order in which the elements are enqueued is the order in which the elements are dequeued. Therefore, if you want to get the last element enqueued, you need to first dequeue all previous elements. Therefore, in order to use two queues to implement the stack, we need to use one of the queues store_queue
to store elements, and the other queue temp_queue
to save the temporary output in order to obtain the last element. Team elements. push
The operation enqueues the given element into the storage queue store_queue
; the pop
operation first removes the last element from the storage queue store_queue
All elements outside the queue are transferred to the temporary queue temp_queue
, and then the last element in the storage queue store_queue
is dequeued and returned. The specific operation is shown in the figure below:
#[Algorithm]
算法运行过程需要始终保持其中一个队列为空,用作临时队列
入栈push
:在非空队列中插入元素data
。
若队列queue_1
为空:
将data
插入 队列queue_2
中
否则:
将data
插入 队列queue_1
中
出栈pop
:将队列中的前n−1 个元素插入另一队列,删除并返回最后一个元素
若队列queue_1
不为空:
将队列queue_1
的前n−1 个元素插入queue_2
,然后queue_1
的最后一个元素出队并返回
若队列queue_2
不为空:
将队列queue_2
的前 n−1 个元素插入queue_1
,然后queue_2
的最后一个元素出队并返回
[代码]
class Stack: def __init__(self): self.queue_1 = Queue() self.queue_2 = Queue() def isempty(self): return self.queue_1.isempty() and self.queue_2.isempty() def push(self, data): if self.queue_2.isempty(): self.queue_1.enqueue(data) else: self.queue_2.enqueue(data) def pop(self): if self.isempty(): raise IndexError("Stack is empty") elif self.queue_2.isempty(): while not self.queue_1.isempty(): p = self.queue_1.dequeue() if self.queue_1.isempty(): return p self.queue_2.enqueue(p) else: while not self.queue_2.isempty(): p = self.queue_2.dequeue() if self.queue_2.isempty(): return p self.queue_1.enqueue(p)
[时空复杂度] push
操作的时间复杂度为O(1),由于 pop
操作时,都需要将所有元素从一个队列转移到另一队列,因此时间复杂度O(n)。
3. 栈中元素连续性判断
[问题] 给定一栈 stack1
,栈中元素均为整数,判断栈中每对连续的数字是否为连续整数(如果栈有奇数个元素,则排除栈顶元素)。例如,输入栈 [1, 2, 5, 6, -5, -4, 11, 10, 55]
,输入为 True
,因为排除栈顶元素 55
后,(1, 2)
、(5, 6)
、(-5, -4)
、(11, 10)
均为连续整数。
[思路] 由于栈中可能存在奇数个元素,因此为了正确判断,首次需要将栈中元素反转,栈顶元素变为栈底,然后依次出栈,进行判断。
[算法]
栈
stack
中所有元素依次出栈,并插入队列queue
中
队列queue
中所有元素出队,并入栈stack
while 栈stack
不为空:
栈顶元素e1
出栈,并插入队列queue
中
如果栈stack
不为空:
栈顶元素e2
出栈,并插入队列queue
中
如果|e1-e2|!=1
:
返回False
,跳出循环
队列queue
中所有元素出队,并入栈stack
[代码]
def check_stack_pair(stack): queue = Queue() flag = True # 反转栈中元素 while not stack.isempty(): queue.enqueue(stack.pop()) while not queue.isempty(): stack.push(queue.dequeue()) while not stack.isempty(): e1 = stack.pop() queue.enqueue(e1) if not stack.isempty(): e2 = stack.pop() queue.enqueue(e2) if abs(e1-e2) != 1: flag = False break while not queue.isempty(): stack.push(queue.dequeue()) return flag
[时空复杂度] 时间复杂度为 O(n),空间复杂度为 O(n)。
4. Lets analyze Python queue-related applications and exercises together
[问题] 给定一个整数队列 queue
,将队列的前半部分与队列的后半部分交错来重新排列元素。例如输入队列为 [1, 2, 3, 4, 5, 6, 7, 8, 9]
,则输出应为 [1, 6, 2, 7, 3, 8, 4, 9, 5]
。
[思路] 通过获取队列的前半部分,然后利用栈的反转特性,可以实现重排操作,如下图所示:
[算法]
如果队列
queue
中的元素数为偶数:
half=queue.size//2
否则:
half=queue.size//2+1
1. 将队列queue
的前半部分元素依次出队并入栈stack
2. 栈stack
中元素出栈并入队queue
3. 将队列queue
中在步骤 1
中未出队的另一部分元素依次出队并插入队尾
4. 将队列queue
的前半部分元素依次出队并入栈stack
5. 将栈stack
和队列queue
中的元素交替弹出并入队
6. 如果栈stack
非空:
栈stack
中元素出栈并入队
[代码]
def queue_order(queue): stack = Stack() size = queue.size if size % 2 == 0: half = queue.size//2 else: half = queue.size//2 + 1 res = queue.size - half for i in range(half): stack.push(queue.dequeue()) while not stack.isempty(): queue.enqueue(stack.pop()) for i in range(res): queue.enqueue(queue.dequeue()) for i in range(half): stack.push(queue.dequeue()) for i in range(res): queue.enqueue(stack.pop()) queue.enqueue(queue.dequeue()) if not stack.isempty(): queue.enqueue(stack.pop())
[时空复杂度] 时间复杂度为O(n),空间复杂度为 O(n)。
5. 反转队列中前 m 个元素的顺序
[问题] 给定一个整数 m
和一个整数队列 queue
,反转队列中前 k 个元素的顺序,而其他元素保持不变。如 m=5
,队列为 [1, 2, 3, 4, 5, 6, 7, 8, 9]
,算法输出为 [5, 4, 3, 2, 1, 6, 7, 8, 9]
。
[思路] 结合 [问题4] 我们可以发现,此题就是 [问题4] 的前 3
步,如下图所示:
[算法]
1. 将队列
queue
的前m
个元素依次出队并入栈stack
2. 栈stack
中元素出栈并入队queue
3. 将队列queue
中在步骤 1
中未出队的另一部分元素依次出队并插入队尾
[代码]
def reverse_m_element(queue, m): stack = Stack() size = queue.size if queue.isempty() or m>size: return for i in range(m): stack.push(queue.dequeue()) while not stack.isempty(): queue.enqueue(stack.pop()) for i in range(size-m): queue.enqueue(queue.dequeue())
[时空复杂度] 时间复杂度为O(n),空间复杂度为 O(n)。
Recommended learning: python tutorial
The above is the detailed content of Let's analyze Python queue-related applications and exercises together. For more information, please follow other related articles on the PHP Chinese website!

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment