فهم Lists الانتظار (Queues) في بايثون: دليل المبتدئين الشامل
مرحباً بك في درس اليوم! سنتعرف على أحد أهم هياكل البيانات الأساسية التي ستواجهها في البرمجة، وهي Lists الانتظار أو Queues. تخيل أنك تقف في طابور لشراء قهوة. أول شخص يصل هو أول من يخدم ويغادر. هذا بالضبط المبدأ الذي تعمل به Lists الانتظار في البرمجة!
ما هي List الانتظار (Queue)؟
List الانتظار (Queue) هي هيكل بيانات خطي يتبع مبدأ أول ما يدخل هو أول ما يخرج (FIFO - First-In, First-Out). هذا يعني أن العنصر الذي تمت إضافته أولاً إلى الـ List سيكون هو أول عنصر يتم إزالته منها.
العمليات الأساسية لـ List الانتظار:
- الإضافة (Enqueue): إضافة عنصر جديد إلى نهاية List الانتظار.
- الإزالة (Dequeue): إزالة العنصر الموجود في مقدمة List الانتظار.
- معاينة المقدمة (Peek/Front): الحصول على قيمة العنصر في المقدمة دون إزالته.
- الفحص (isEmpty): التحقق مما إذا كانت List الانتظار فارغة.
تنفيذ List انتظار من الصفر (Custom Queue)
فهم كيفية بناء هيكل البيانات بنفسك هو أفضل طريقة لإتقان مبادئه. دعونا ننشئ صنف Queue خاص بنا.
1. هيكل الصنف الأساسي
سنبدأ بإنشاء الصنف وتهيئة الـ List الداخلية التي ستخزن البيانات.
class Queue:
def __init__(self):
# Internal list to store queue elements
self.items = []
def is_empty(self):
"""Check if the queue is empty"""
return len(self.items) == 0
تنفيذ العمليات الأساسية على Lists الانتظار
الآن سنقوم بتطبيق العمليات الرئيسية: الإضافة (Enqueue)، والإزالة (Dequeue)، والمعاينة (Peek).
1. إضافة عناصر (Enqueue)
تتم الإضافة دائمًا إلى نهاية List الانتظار.
class Queue:
# ... (previous code)
def enqueue(self, item):
"""Add a new item to the end of the queue"""
self.items.append(item) # Use append to add to the end
print(f"Added: {item}") # Comment: Print confirmation of addition
2. إزالة عنصر (Dequeue)
تتم الإزالة دائمًا من مقدمة List الانتظار (العنصر الأقدم).
class Queue:
# ... (previous code)
def dequeue(self):
"""Remove and return the item from the front of the queue"""
if self.is_empty():
print("Warning: Queue is empty!")
return None # Comment: Return None if the queue is empty
return self.items.pop(0) # Use pop(0) to remove the first item
3. معاينة العنصر الأمامي (Peek)
ننظر إلى العنصر الموجود في المقدمة دون إزالته من الـ List.
class Queue:
# ... (previous code)
def peek(self):
"""Return the element at the front of the queue without removing it"""
if self.is_empty():
print("Queue is empty, no element to peek.")
return None
return self.items[0] # Comment: Access the first element directly
def size(self):
"""Return the number of elements in the queue"""
return len(self.items)
مثال تطبيقي: محاكاة طابور خدمة العملاء
لنرى كيف يعمل تنفيذنا الجديد في مثال حيوي.
# Create an instance of our queue
customer_queue = Queue()
# Add customers to the queue
print("--- Customer Arrival ---")
customer_queue.enqueue("Ahmed")
customer_queue.enqueue("Sarah")
customer_queue.enqueue("Khaled")
print(f"\nNext customer for service: {customer_queue.peek()}")
print(f"Number of customers in queue: {customer_queue.size()}")
# Serve customers
print("\n--- Starting Service ---")
served = customer_queue.dequeue()
print(f"Served customer: {served}")
print(f"After service, next is: {customer_queue.peek()}")
# Add a new customer during service
print("\n--- New Customer Arrival ---")
customer_queue.enqueue("Noura")
print(f"Number of customers now: {customer_queue.size()}")
# Serve remaining customers
print("\n--- Completing Service ---")
while not customer_queue.is_empty():
served = customer_queue.dequeue()
print(f"Served: {served}")
print(f"\nFinal state. Is the queue empty? {customer_queue.is_empty()}")
استخدام الـ Lists المدمجة (List) مباشرة
للمقارنة، هذه هي الطريقة السريعة لاستخدام الـ List (list) كـ List انتظار دون إنشاء صنف مخصص.
# Create an empty queue
my_queue = []
# Add elements (Enqueue)
my_queue.append("Task 1")
my_queue.append("Task 2")
# Remove element (Dequeue)
next_task = my_queue.pop(0) # Comment: Remove the first element
print("Next task:", next_task)
# Preview (Peek)
if my_queue: # Comment: Shortcut to check if the list is not empty
print("Element at the front:", my_queue[0])
استخدام Module queue الرسمية في بايثون
بينما الـ Lists (list) وتنفيذنا المخصص يعملان، إلا أن استخدام pop(0) غير فعال للبيانات الضخمة. توفر بايثون Module queue مع صنف Queue الأمثل.
import queue
# Create Queue object
my_better_queue = queue.Queue()
# Enqueue
my_better_queue.put("file 1")
my_better_queue.put("file 2")
# Dequeue
processed_item = my_better_queue.get()
print("Processed:", processed_item)
# Check if empty
print("Is empty?", my_better_queue.empty())
ملاحظة: queue.Queue مصمم للبرمجة المتوازية (thread-safe). للمشاريع التعليمية والبسيطة، التنفيذ المخصص أو استخدام الـ Lists مباشرة كافٍ.
ملخص سريع ومقارنة
- المبدأ: FIFO (أول ما يدخل هو أول ما يخرج).
- التنفيذ المخصص: بناء صنف
Queueبأساليبenqueue()،dequeue()، وpeek()يعمق الفهم. - باستخدام List مباشرة:
append()للإضافة،pop(0)للإزالة (انتبه للأداء). - الـ Module الرسمية
queue:queue.Queueهو الحل الأمثل والآمن للتطبيقات الحقيقية والمعقدة.
اختبر معلوماتك
أسئلة قصيرة تتأكد بها من فهمك للدرس قبل أن تنتقل.
التعليقات
شاركنا رأيك أو أسئلتك حول هذا المحتوى