ENع
→Ring buffers
الدرس 08 · Linear structures in depth

Ring buffers and deques under the hood

لم يُترجم بعد؛ يُعرض باللغة الإنجليزية

12 دقيقة10 خطوات5 أسئلةBeginner
عن هذا الدرس

A queue that never shifts its items. Keep them in a fixed Python list of 8 slots, remember where the front is (head) and how many there are (size), and let the % operator join the end of the list to its start. Push and pop each touch one slot, so both take the same time however long the queue is. The Software lesson "Stacks and queues" shows why list.pop(0) is slow and introduces collections.deque; this lesson builds that fast queue by hand, then adds the second end that makes a deque.

ستتعلّم

حدّد ما تشعر بأنك أتقنته. هذا التقييم الذاتي لا يؤثر في درجة الدرس.

شكل 8 · تفاعلي
01 / 10

Eight slots in a ring

A queue adds at the back and takes from the front. Here it lives in a plain Python list of 8 slots, numbered 0 to 7. q.head is the slot of the front item; q.size counts the items. Both start at 0.

setup (runs before the card):
  from types import SimpleNamespace
  CAP = 8
  q = SimpleNamespace(buf=[None] * CAP, head=0, size=0)


slots 0:· 1:· 2:· 3:· 4:· 5:· 6:· 7:·
head = 0  size = 0  tail = (0 + 0) % 8 = 0
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. Eight slots in a ring

    A queue adds at the back and takes from the front. Here it lives in a plain Python list of 8 slots, numbered 0 to 7. q.head is the slot of the front item; q.size counts the items. Both start at 0.

    setup (runs before the card):
      from types import SimpleNamespace
      CAP = 8
      q = SimpleNamespace(buf=[None] * CAP, head=0, size=0)
    
    
    slots 0:· 1:· 2:· 3:· 4:· 5:· 6:· 7:·
    head = 0  size = 0  tail = (0 + 0) % 8 = 0
  2. Push adds at the back

    push finds the back slot: tail = (head + size) % 8. With head at 0 that gives slots 0, 1 and 2 for A, B and C. Each push writes one slot and adds 1 to size: one step, however long the queue is.

    tail = (0 + 0) % 8 = 0, then 1, then 2
    push(q, "A") -> slot 0
    push(q, "B") -> slot 1
    push(q, "C") -> slot 2
    
    slots 0:A 1:B 2:C 3:· 4:· 5:· 6:· 7:·
    head = 0  size = 3  tail = (0 + 3) % 8 = 3
  3. Pop takes from the front

    pop returns the item in slot head, then moves head on by one. A and B leave; head goes 0, 1, 2. Nothing else moves: C stays in slot 2. A list's pop(0) would shift every item left instead.

    head = (head + 1) % 8: 0 -> 1 -> 2
    pop() -> A  (slot 0, head -> 1)
    pop() -> B  (slot 1, head -> 2)
    
    slots 0:· 1:· 2:C 3:· 4:· 5:· 6:· 7:·
    head = 2  size = 1  tail = (2 + 1) % 8 = 3
  4. Fill to the end

    Push D, E, F, G and H. They land in slots 3 to 7, the last slots of the list. Now head is 2 and size is 6, so the queue holds C to H, front to back.

    push(q, "D") -> slot 3
    push(q, "E") -> slot 4
    push(q, "F") -> slot 5
    push(q, "G") -> slot 6
    push(q, "H") -> slot 7
    
    slots 0:· 1:· 2:C 3:D 4:E 5:F 6:G 7:H
    head = 2  size = 6  tail = (2 + 6) % 8 = 0
  5. Wrap around with %

    Push I: tail = (2 + 6) % 8 = 0. The % gives the remainder after dividing, so 8 becomes 0 and I goes back to slot 0, which A left free. The end of the list joins its start: a ring.

    tail = (2 + 6) % 8 = 8 % 8 = 0
    push(q, "I") -> slot 0
    
    slots 0:I 1:· 2:C 3:D 4:E 5:F 6:G 7:H
    head = 2  size = 7  tail = (2 + 7) % 8 = 1
  6. Full: tail meets head

    Push J into slot 1. Now size is 8 and tail = (2 + 8) % 8 = 2, the same slot as head. head and tail also meet when the queue is empty, so size is what tells full from empty.

    empty: size 0, tail == head
    full:  size 8, tail == head
    push(q, "J") -> slot 1
    
    slots 0:I 1:J 2:C 3:D 4:E 5:F 6:G 7:H
    head = 2  size = 8  tail = (2 + 8) % 8 = 2
  7. One push too many

    Push K finds size == CAP and raises an error instead of writing over C, the front item. A growing queue would copy all 8 items into a list twice as big; a bounded deque drops the oldest item instead.

    size == CAP, so push raises before it writes
    
    push(q, "K") -> IndexError: full
    
    slots 0:I 1:J 2:C 3:D 4:E 5:F 6:G 7:H
    head = 2  size = 8  tail = (2 + 8) % 8 = 2
  8. The front wraps too

    Pop six times: C, D, E, F, G and H come out. head counts 3, 4, 5, 6, 7, then (7 + 1) % 8 = 0. Now the front is I in slot 0, with J behind it.

    head = (7 + 1) % 8 = 0 on the last pop
    pop() -> C  (slot 2, head -> 3)
    pop() -> D  (slot 3, head -> 4)
    pop() -> E  (slot 4, head -> 5)
    pop() -> F  (slot 5, head -> 6)
    pop() -> G  (slot 6, head -> 7)
    pop() -> H  (slot 7, head -> 0)
    
    slots 0:I 1:J 2:· 3:· 4:· 5:· 6:· 7:·
    head = 0  size = 2  tail = (0 + 2) % 8 = 2
  9. Push at the front

    A deque (a double-ended queue) can also add at the front: head = (head - 1) % 8. In Python -1 % 8 is 7, so Z goes into slot 7, just before I. Both ends take one step.

    push_front (not on the card):
      def push_front(q, x):
          if q.size == CAP:
              raise IndexError("full")
          q.head = (q.head - 1) % CAP
          q.buf[q.head] = x
          q.size += 1
    
    (0 - 1) % 8 = 7 in Python
    
    push_front(q, "Z") -> slot 7
    
    slots 0:I 1:J 2:· 3:· 4:· 5:· 6:· 7:Z
    head = 7  size = 3  tail = (7 + 3) % 8 = 2
  10. Python's deque

    You rarely write this by hand: collections.deque has append, appendleft, pop and popleft, each O(1). Inside CPython it is a chain of 64-slot blocks rather than one ring, but the idea is the same: the ends move, the items stay.

    from collections import deque
    d = deque("IJ")
    d.appendleft("Z")    # deque(['Z', 'I', 'J'])
    d.append("L")        # back
    d.popleft()          # 'Z', the front
    
    list.pop(0) shifts every item: O(n)
    deque.popleft() moves none:   O(1)

اختبار يتاح بعد الخطوة الأخيرة.