Hướng dẫn built in python data type to represent a queue - được xây dựng trong kiểu dữ liệu python để đại diện cho một hàng đợi

Hàng đợi là một cấu trúc dữ liệu tuyến tính lưu trữ các mục theo cách từ đầu/từ đầu (FIFO). Trong hàng đợi, phần tử dữ liệu được chèn trước sẽ được xóa trước. is a linear data structure that stores items in a First-In/First Out(FIFO) manner. In queue, the data element that is inserted first will be removed first.

Show

Các hoạt động có thể được thực hiện trên hàng đợi là:

  1. # Implement Queue using List(Functions)

    q=[]

    def Enqueue():

    if len(q)==size: # check wether the stack is full or not

    print("Queue is Full!!!!")

    else:

    element=input("Enter the element:")

    q.append(element)

    print(element,"is added to the Queue!")

    def dequeue():

    if not q:# or if len(stack)==0

    print("Queue is Empty!!!")

    else:

    e=q.pop(0)

    print("element removed!!:",e)

    def display():

    print(q)

    size=int(input("Enter the size of Queue:"))

    while True:

    print("Select the Operation:1.Add 2.Delete 3. Display 4. Quit")

    choice=int(input())

    if choice==1:

    Enqueue()

    elif choice==2:

    dequeue()

    elif choice==3:

    display()

    elif choice==4:

    break

    else:

    print("Invalid Option!!!")

    0: Nó thêm một mục vào hàng đợi. Nếu hàng đợi đầy, thì nó được cho là một điều kiện tràn.: It adds an item to the queue. If the queue is full, then it is said to be an Overflow condition.

  2. # Implement Queue using List(Functions)

    q=[]

    def Enqueue():

    if len(q)==size: # check wether the stack is full or not

    print("Queue is Full!!!!")

    else:

    element=input("Enter the element:")

    q.append(element)

    print(element,"is added to the Queue!")

    def dequeue():

    if not q:# or if len(stack)==0

    print("Queue is Empty!!!")

    else:

    e=q.pop(0)

    print("element removed!!:",e)

    def display():

    print(q)

    size=int(input("Enter the size of Queue:"))

    while True:

    print("Select the Operation:1.Add 2.Delete 3. Display 4. Quit")

    choice=int(input())

    if choice==1:

    Enqueue()

    elif choice==2:

    dequeue()

    elif choice==3:

    display()

    elif choice==4:

    break

    else:

    print("Invalid Option!!!")

    1: Nó loại bỏ một mục khỏi hàng đợi. Các mục được xuất hiện theo cùng một thứ tự mà chúng được đẩy. Nếu hàng đợi trống, thì nó được cho là một điều kiện dòng chảy.: It removes an item from the queue. The items are popped in the same order in which they are pushed. If the queue is empty, then it is said to be an Underflow condition.

  3. # Implement Queue using List(Functions)

    q=[]

    def Enqueue():

    if len(q)==size: # check wether the stack is full or not

    print("Queue is Full!!!!")

    else:

    element=input("Enter the element:")

    q.append(element)

    print(element,"is added to the Queue!")

    def dequeue():

    if not q:# or if len(stack)==0

    print("Queue is Empty!!!")

    else:

    e=q.pop(0)

    print("element removed!!:",e)

    def display():

    print(q)

    size=int(input("Enter the size of Queue:"))

    while True:

    print("Select the Operation:1.Add 2.Delete 3. Display 4. Quit")

    choice=int(input())

    if choice==1:

    Enqueue()

    elif choice==2:

    dequeue()

    elif choice==3:

    display()

    elif choice==4:

    break

    else:

    print("Invalid Option!!!")

    2: Nó cung cấp cho mục trước từ hàng đợi.: It gives the front item from the queue.

  4. # Implement Queue using List(Functions)

    q=[]

    def Enqueue():

    if len(q)==size: # check wether the stack is full or not

    print("Queue is Full!!!!")

    else:

    element=input("Enter the element:")

    q.append(element)

    print(element,"is added to the Queue!")

    def dequeue():

    if not q:# or if len(stack)==0

    print("Queue is Empty!!!")

    else:

    e=q.pop(0)

    print("element removed!!:",e)

    def display():

    print(q)

    size=int(input("Enter the size of Queue:"))

    while True:

    print("Select the Operation:1.Add 2.Delete 3. Display 4. Quit")

    choice=int(input())

    if choice==1:

    Enqueue()

    elif choice==2:

    dequeue()

    elif choice==3:

    display()

    elif choice==4:

    break

    else:

    print("Invalid Option!!!")

    3: Nó cung cấp cho mục cuối cùng từ hàng đợi.: It gives the last item from the queue.

Lưu ý: Độ phức tạp về thời gian cho tất cả các hoạt động trên là O (1).

Thực hiện

Hàng đợi trong Python có thể được thực hiện theo những cách sau:

  1. # Implement Queue using List(Functions)

    q=[]

    def Enqueue():

    if len(q)==size: # check wether the stack is full or not

    print("Queue is Full!!!!")

    else:

    element=input("Enter the element:")

    q.append(element)

    print(element,"is added to the Queue!")

    def dequeue():

    if not q:# or if len(stack)==0

    print("Queue is Empty!!!")

    else:

    e=q.pop(0)

    print("element removed!!:",e)

    def display():

    print(q)

    size=int(input("Enter the size of Queue:"))

    while True:

    print("Select the Operation:1.Add 2.Delete 3. Display 4. Quit")

    choice=int(input())

    if choice==1:

    Enqueue()

    elif choice==2:

    dequeue()

    elif choice==3:

    display()

    elif choice==4:

    break

    else:

    print("Invalid Option!!!")

    4
  2. # Implement Queue using List(Functions)

    q=[]

    def Enqueue():

    if len(q)==size: # check wether the stack is full or not

    print("Queue is Full!!!!")

    else:

    element=input("Enter the element:")

    q.append(element)

    print(element,"is added to the Queue!")

    def dequeue():

    if not q:# or if len(stack)==0

    print("Queue is Empty!!!")

    else:

    e=q.pop(0)

    print("element removed!!:",e)

    def display():

    print(q)

    size=int(input("Enter the size of Queue:"))

    while True:

    print("Select the Operation:1.Add 2.Delete 3. Display 4. Quit")

    choice=int(input())

    if choice==1:

    Enqueue()

    elif choice==2:

    dequeue()

    elif choice==3:

    display()

    elif choice==4:

    break

    else:

    print("Invalid Option!!!")

    5
  3. # Implement Queue using List(Functions)

    q=[]

    def Enqueue():

    if len(q)==size: # check wether the stack is full or not

    print("Queue is Full!!!!")

    else:

    element=input("Enter the element:")

    q.append(element)

    print(element,"is added to the Queue!")

    def dequeue():

    if not q:# or if len(stack)==0

    print("Queue is Empty!!!")

    else:

    e=q.pop(0)

    print("element removed!!:",e)

    def display():

    print(q)

    size=int(input("Enter the size of Queue:"))

    while True:

    print("Select the Operation:1.Add 2.Delete 3. Display 4. Quit")

    choice=int(input())

    if choice==1:

    Enqueue()

    elif choice==2:

    dequeue()

    elif choice==3:

    display()

    elif choice==4:

    break

    else:

    print("Invalid Option!!!")

    6

# implementing Queue using List :

q=[]

q.append(10)

q.append(100)

q.append(1000)

q.append(10000)

print("Initial Queue is:",q)

print(q.pop(0))

print(q.pop(0))

print(q.pop(0))

print("After Removing elements:",q)

Mã để thực hiện hàng đợi bằng danh sách

# Implement Queue using List(Functions)

q=[]

def Enqueue():

if len(q)==size: # check wether the stack is full or not

print("Queue is Full!!!!")

else:

element=input("Enter the element:")

q.append(element)

print(element,"is added to the Queue!")

def dequeue():

if not q:# or if len(stack)==0

print("Queue is Empty!!!")

else:

e=q.pop(0)

print("element removed!!:",e)

def display():

print(q)

size=int(input("Enter the size of Queue:"))

while True:

print("Select the Operation:1.Add 2.Delete 3. Display 4. Quit")

choice=int(input())

if choice==1:

Enqueue()

elif choice==2:

dequeue()

elif choice==3:

display()

elif choice==4:

break

else:

print("Invalid Option!!!")

Mã để thực hiện hàng đợi bằng danh sách

# implment queue using queue module

from queue import Queue

q=Queue(maxsize=4)

print("Initial Size Before Insertion:",q.qsize())

q.put('A')

q.put('AA')

q.put('AAA')

q.put('AAAA')

print("After Insertion:",q.qsize())

print("Queue is Full or Not:",q.full())

print("Size of Queue:",q.qsize())

print("Removing Elements:")

print(q.get())

print(q.get())

print(q.get())

print("Empty or Not??",q.empty())

print(q.get())

print("Empty or Not??",q.empty())

print("Size of Queue:",q.qsize())

Mã để thực hiện hàng đợi bằng mô -đun hàng đợi

from collections import deque

q=deque()

q.append(10)

q.append(100)

q.append(1000)

q.append(10000)

print("Initial Queue is:",q)

print(q.popleft())

print(q.popleft())

print("After Removing elements:",q)

Mã để thực hiện hàng đợi bằng mô -đun deque

# Triển khai hàng đợi bằng danh sách (chức năng) Q = [] def enqueue (): Nếu len (q) == kích thước: # Kiểm tra wether ngăn xếp có đầy đủ hay không. ....

# Hàng đợi sử dụng mô -đun hàng đợi. Từ hàng đợi hàng đợi hàng đợi. Q = Hàng đợi (MaxSize = 4) ....

từ bộ sưu tập nhập khẩu deque. Q = deque () Q ..First in First Out". It is also known as "first come first severed". The queue has the two ends front and rear. The next element is inserted from the rear end and removed from the front end.

Trong hướng dẫn này, chúng tôi sẽ thảo luận về các khái niệm cơ bản của hàng đợi và lớp hàng đợi tích hợp và thực hiện nó bằng mã Python. There are 20 computers in the computer science lab and connected to a single printer. The students want to print their paper; the printer will print the first task and second, so on. If we are the last in line, we need to wait until all other tasks are completed that ahead of ours.

Hàng đợi là gì?

Hàng đợi là một loại cấu trúc dữ liệu tuyến tính được sử dụng để lưu trữ dữ liệu theo tuần tự. Khái niệm về hàng đợi dựa trên FIFO, có nghĩa là "đầu tiên ở đầu tiên". Nó còn được gọi là "lần đầu tiên đến bị cắt đứt". Hàng đợi có hai đầu phía trước và phía sau. Phần tử tiếp theo được chèn từ phía sau và loại bỏ khỏi đầu phía trước.

Ví dụ: có 20 máy tính trong phòng thí nghiệm khoa học máy tính và được kết nối với một máy in. Các sinh viên muốn in giấy của họ; Máy in sẽ in nhiệm vụ đầu tiên và thứ hai, vì vậy. Nếu chúng ta là người cuối cùng, chúng ta cần đợi cho đến khi tất cả các nhiệm vụ khác được hoàn thành trước chúng ta.

  • Hệ điều hành quản lý hàng đợi để xử lý các quy trình khác nhau trong máy tính. The enqueue is an operation where we add items to the queue. If the queue is full, it is a condition of the Queue The time complexity of enqueue is O(1).
  • Hoạt động trong Python The dequeue is an operation where we remove an element from the queue. An element is removed in the same order as it is inserted. If the queue is empty, it is a condition of the Queue Underflow. The time complexity of dequeue is O(1).
  • Chúng tôi có thể thực hiện các hoạt động sau trong hàng đợi. An element is inserted in the front end. The time complexity of front is O(1).
  • Enqueue - Enqueue là một hoạt động nơi chúng tôi thêm các mục vào hàng đợi. Nếu hàng đợi đầy đủ, đó là điều kiện của hàng đợi độ phức tạp về thời gian của enqueue là O (1). An element is removed from the rear end.. The time complexity of the rear is O(1).

Dequeue - Dequeue là một hoạt động trong đó chúng tôi loại bỏ một phần tử khỏi hàng đợi. Một phần tử được loại bỏ theo cùng thứ tự như được chèn. Nếu hàng đợi trống, đó là điều kiện của hàng đợi. Độ phức tạp thời gian của dequeue là O (1).

Mặt trước - Một phần tử được chèn vào mặt trước. Độ phức tạp thời gian của mặt trước là O (1).

  • Phía sau - Một phần tử được loại bỏ khỏi phía sau .. Độ phức tạp của thời gian của phía sau là O (1). This function is used to insert element to the queue.
  • Các phương pháp có sẵn trong hàng đợi This function is used to extract the element from the queue.
  • Python cung cấp các phương pháp sau, thường được sử dụng để thực hiện hoạt động trong hàng đợi. This function is used to check whether a queue is empty or not. It returns true if queue is empty.
  • Đặt (Mục) - Hàm này được sử dụng để chèn phần tử vào hàng đợi. This function returns the length of the queue.
  • GET () - Hàm này được sử dụng để trích xuất phần tử từ hàng đợi. If the queue is full returns true; otherwise false.

trống () - Hàm này được sử dụng để kiểm tra xem hàng đợi có trống hay không. Nó trả về đúng nếu hàng đợi trống.

Qsize - Hàm này trả về chiều dài của hàng đợi.

full () - nếu hàng đợi hoàn toàn trả về đúng; nếu không thì sai.insert() and pop() function to add and remove elements. Lists are quite slow because if we insert a new element to the list, all elements require shifting by one. It takes O(n) time. So lists are recommended in-place of queue. Let's understand the following example of how a list can be used as a queue.

Thí dụ -

Output:

['Apple', 'Mango', 'Papaya']
Apple

Giải trình -

Chúng tôi đã xác định danh sách trống trong mã trên và chèn một vài phần tử bằng phương thức append (). Nó sẽ thêm một yếu tố vào cuối danh sách.append() method. It will add an element to the end of the list.

Thêm phần tử vào hàng đợi (enqueue)

Chúng ta có thể thêm phần tử từ phía sau. Quá trình này cũng được gọi là Enqueue. Chúng tôi tạo ra một lớp hàng đợi nơi chúng tôi sẽ thực hiện khái niệm đầu tiên. Hãy hiểu ví dụ sau.

Thí dụ -

Output:

Loại bỏ phần tử khỏi hàng đợi (Dequeue)

Chúng ta có thể loại bỏ phần tử Mẫu phía sau. Quá trình này được gọi là một dequeue. Trong ví dụ sau, chúng tôi sử dụng phương thức pop () tích hợp để xóa một phần tử khỏi danh sách.

Thí dụ -

Output:

Giải trình -

Chúng tôi đã xác định danh sách trống trong mã trên và chèn một vài phần tử bằng phương thức append (). Nó sẽ thêm một yếu tố vào cuối danh sách.queue variable. Then, we defined two methods - add_element() and remove_element(). In the add_element() block, we check the condition if the value is not in Queue. If value is not present, insert the element.

Thêm phần tử vào hàng đợi (enqueue)remove_element() function block, we check the condition of whether a queue is not underflow. If it returns false, then remove the element one by one.

Chúng ta có thể thêm phần tử từ phía sau. Quá trình này cũng được gọi là Enqueue. Chúng tôi tạo ra một lớp hàng đợi nơi chúng tôi sẽ thực hiện khái niệm đầu tiên. Hãy hiểu ví dụ sau.

Loại bỏ phần tử khỏi hàng đợi (Dequeue)

Thí dụ -

Output:

Chúng ta có thể loại bỏ phần tử Mẫu phía sau. Quá trình này được gọi là một dequeue. Trong ví dụ sau, chúng tôi sử dụng phương thức pop () tích hợp để xóa một phần tử khỏi danh sách.

Trong mã trên, chúng tôi đã xác định một lớp có tên Hàng đợi và Trình xây dựng trong đó. Chúng tôi đã chỉ định một hàm tạo danh sách cho biến hàng đợi. Sau đó, chúng tôi đã xác định hai phương thức - add_element () và remove_element (). Trong khối add_element (), chúng tôi kiểm tra điều kiện nếu giá trị không có trong hàng đợi. Nếu giá trị không có mặt, chèn phần tử.

Trong khối chức năng remove_element (), chúng tôi kiểm tra điều kiện có hàng đợi không được thực hiện. Nếu nó trả về sai, sau đó xóa từng phần tử một.

Sắp xếp hàng đợi

Trong ví dụ sau, chúng tôi đã sắp xếp các yếu tố của hàng đợi.

Thí dụ -

Output:


Apple
Mango
Papaya
Traceback (most recent call last):
  File "C:/Users/DEVANSH SHARMA/PycharmProjects/Hello/Queue.py", line 78, in 
    print(que.get_nowait())
  File "C:\Python\lib\queue.py", line 198, in get_nowait
    return self.get(block=False)
  File "C:\Python\lib\queue.py", line 167, in get
    raise Empty
_queue.Empty

Các mô -đun hàng đợi

Python cung cấp mô-đun hàng đợi để triển khai hàng đợi đa nhà sản xuất, đa tiêu dùng. Mô -đun hàng đợi cung cấp lớp hàng đợi được sử dụng đặc biệt cho lập trình luồng. Lớp xếp hàng thực hiện tất cả các ngữ nghĩa khóa cần thiết.collection.deque class is used to implement a double-ended queue that supports adding and removing element from both ends. It takes O(1) time to complete the process.

Chúng ta có thể thực hiện tất cả các thao tác bằng cách sử dụng lớp hàng đợi được xây dựng.deque class can be used in both Queue and as stacks because it removes and adds elements effectively.

Làm việc với Lớp xếp hàng.collection.deque can be a good choice for queue data structure in Python's standard library.

Thí dụ -

Output:

deque(['Apple', 'Mango', 'Banana'])
Apple
Mango
Banana
Traceback (most recent call last):
  File "C:/Users/DEVANSH SHARMA/PycharmProjects/Hello/Queue.py", line 101, in 
    que.popleft()
IndexError: pop from an empty deque

Mô -đun hàng đợi chứa một số lớp. Hàng đợi là một trong những lớp quan trọng của chúng. Điều này rất hữu ích trong tính toán song song và đa dạng. Hãy hiểu ví dụ sau đây của hàng đợi. Hàng đợi lớp0UII

Làm việc với Class Collection.Deque Classmulticurrent workers. The multiprocessing.Queue shares data between processes and can store any pickle-able object. Let's understand the following example.

Thí dụ -

Output:


Apple
Mango
Banana

Lớp Collection.deque được sử dụng để triển khai hàng đợi hai kết thúc hỗ trợ thêm và loại bỏ phần tử khỏi cả hai đầu. Phải mất thời gian O (1) để hoàn thành quá trình.

Lớp Deque có thể được sử dụng trong cả hàng đợi và dưới dạng ngăn xếp vì nó loại bỏ và thêm các yếu tố một cách hiệu quả.

Bộ sưu tập.Deque có thể là một lựa chọn tốt cho cấu trúc dữ liệu hàng đợi trong thư viện tiêu chuẩn của Python.

Lớp đa xử lý.queue

Lớp đa xử lý.queue được sử dụng để thực hiện các mục xếp hàng để được xử lý song song bởi các công nhân đa dòng. Multiprocessing.queue chia sẻ dữ liệu giữa các quy trình và có thể lưu trữ bất kỳ đối tượng có thể dưa chua nào. Hãy hiểu ví dụ sau. An operating system task is the best example of a priority queue - It executes the high precedence over lower-priority tasks (downloading updates in the background). The task scheduler can allow the highest-priority tasks to run first.

Hàng đợi ưu tiên trong Python

Hàng đợi ưu tiên là một loại hàng đợi đặc biệt trong cấu trúc dữ liệu. Như tên đề xuất, nó sắp xếp các yếu tố và khử các yếu tố dựa trên các ưu tiên của chúng.

Không giống như hàng đợi bình thường, nó lấy lại yếu tố ưu tiên cao nhất thay vì yếu tố tiếp theo. Ưu tiên của các yếu tố riêng lẻ được quyết định bằng cách đặt hàng áp dụng cho khóa của họ.O(n) operations.

Hàng đợi ưu tiên có lợi nhất để xử lý các vấn đề lập kế hoạch trong đó một số nhiệm vụ sẽ xảy ra dựa trên các ưu tiên.

Ví dụ: Nhiệm vụ hệ điều hành là ví dụ tốt nhất về hàng đợi ưu tiên - nó thực hiện ưu tiên cao so với các nhiệm vụ ưu tiên thấp hơn (tải xuống các bản cập nhật trong nền). Trình lập lịch tác vụ có thể cho phép các nhiệm vụ ưu tiên cao nhất chạy trước.

Thí dụ -

Output:

(1, 'Mango')
(2, 'Apple')
(3, 'Banana')

Có nhiều cách khác nhau để thực hiện hàng đợi ưu tiên trong Python. Hãy hiểu những cách sau đây.

Danh sách được sắp xếp thủ côngheapq internally and shares the same time and space complexities.

Chúng ta có thể sử dụng danh sách Python được sắp xếp làm hàng đợi ưu tiên để nhanh chóng xác định và xóa phần tử nhỏ hơn và lớn nhất. Nhưng chèn phần tử mới là chậm khi thực hiện các hoạt động O (N).

Thí dụ -

Output:

(1, 'Banana')
(2, 'Apple')
(3, 'Mango')

Do đó, danh sách được sắp xếp có thể có hiệu quả khi sẽ có một vài phần chèn vào hàng đợi ưu tiên.queue.PriorityQueue is good default choice.

Hãy hiểu ví dụ sau -

Các hàng đợi.Priorityqueue


Làm cách nào để hiển thị hàng đợi trong Python?

Cấu trúc dữ liệu Python: Tạo hàng đợi và hiển thị tất cả các thành viên và kích thước của hàng đợi..
Giải pháp mẫu:.
Mã Python: nhập hàng đợi Q = hàng đợi.queue () cho x trong phạm vi (4): q.put (x) in ("thành viên của hàng đợi:") y = z = q.qsize () cho n trong danh sách (danh sách q.queue): in (n, end = "") in ("\ nsize của hàng đợi:") in (q.qsize ()) ....
Flowchart:.

Loại dữ liệu của hàng đợi là gì?

Hàng đợi là một ví dụ về cấu trúc dữ liệu tuyến tính, hoặc trừu tượng hơn là một bộ sưu tập tuần tự.linear data structure, or more abstractly a sequential collection.

Python có hàng đợi không?

Python cung cấp hàng đợi lớp như một mô -đun thường được tạo bằng các ngôn ngữ như C/C ++ và Java.Khởi tạo một biến đến kích thước tối đa của tối đa.Tối đa hóa bằng 0 '0' có nghĩa là hàng đợi vô hạn.Hàng đợi này tuân theo quy tắc của FIFO. which has to be generally created in languages such as C/C++ and Java. Initializes a variable to a maximum size of maxsize. A maxsize of zero '0' means a infinite queue. This Queue follows FIFO rule.

Làm thế nào để bạn tạo một hàng đợi trong Python?

# Thực hiện hàng đợi bằng danh sách: q = [] q.nối (10) ....
# Triển khai hàng đợi bằng danh sách (chức năng) Q = [] def enqueue (): Nếu len (q) == kích thước: # Kiểm tra wether ngăn xếp có đầy đủ hay không.....
# Hàng đợi sử dụng mô -đun hàng đợi.Từ hàng đợi hàng đợi hàng đợi.Q = Hàng đợi (MaxSize = 4) ....
từ bộ sưu tập nhập khẩu deque.Q = deque () Q ..