Home  >  Article  >  Backend Development  >  Let’s analyze Python queue-related applications and exercises together

Let’s analyze Python queue-related applications and exercises together

WBOY
WBOYforward
2022-03-30 18:35:142327browse

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.

Let’s analyze Python queue-related applications and exercises together

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:

Let’s analyze Python queue-related applications and exercises together

[Algorithm]

Enqueueenqueue:
  Push elements onto the stack stack_1
  Dequeue dequeue:
   If the stack stack_2 is not empty:
     stack_2 Pop the top element from the stack
      Otherwise:
       Pop all elements from stack_1 and push them into stack_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:

Let’s analyze Python queue-related applications and exercises together

#[Algorithm]

 算法运行过程需要始终保持其中一个队列为空,用作临时队列
 入栈 push:在非空队列中插入元素 data
   若队列 queue_1 为空:
     将 data 插入 队列 queue_2
   否则:
     将 data 插入 队列 queue_1
 出栈 pop:将队列中的前n1 个元素插入另一队列,删除并返回最后一个元素
   若队列 queue_1 不为空:
     将队列 queue_1 的前n1 个元素插入 queue_2,然后 queue_1 的最后一个元素出队并返回
   若队列 queue_2 不为空:
     将队列 queue_2 的前 n1 个元素插入 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. Let’s 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]

[思路] 通过获取队列的前半部分,然后利用栈的反转特性,可以实现重排操作,如下图所示:

Let’s analyze Python queue-related applications and exercises together

[算法]

 如果队列 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 步,如下图所示:

反转队列中前 m 个元素的顺序

[算法]

 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!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete