Consider a circular buffer of size 4 initialized with zeros. We write the values [1, 2, 3, 4, 5] sequentially. What will be the buffer content after all writes?
buffer = [0, 0, 0, 0] size = 4 write_pos = 0 values = [1, 2, 3, 4, 5] for v in values: buffer[write_pos] = v write_pos = (write_pos + 1) % size print(buffer)
Remember the buffer overwrites old values when full.
The buffer size is 4. Writing 5 values means the first value (1) is overwritten by the last (5), resulting in [5, 2, 3, 4].
A circular buffer of size 6 starts empty. After writing 4 samples, how many valid samples does it contain?
size = 6 valid_samples = 0 write_count = 4 valid_samples = min(write_count, size) print(valid_samples)
The buffer cannot have more valid samples than its size.
Since only 4 samples are written and buffer size is 6, valid samples count is 4.
What error will this code raise when reading from the circular buffer?
buffer = [10, 20, 30] size = 3 read_pos = 3 value = buffer[read_pos] print(value)
buffer = [10, 20, 30] size = 3 read_pos = 3 value = buffer[read_pos] print(value)
Check if the read position is within valid index range.
Index 3 is out of range for a list of size 3 (indices 0 to 2), causing IndexError.
Which is the main advantage of using a circular buffer for streaming data?
Think about memory use and continuous data flow.
Circular buffers reuse fixed memory by overwriting oldest data, enabling efficient streaming without growing memory.
Given a circular buffer of size 5 with values [4, 7, 2, 9, 5] and a write position at index 2, what is the average of the last 3 samples written?
buffer = [4, 7, 2, 9, 5] size = 5 write_pos = 2 n = 3 # Calculate indices of last n samples indices = [(write_pos - i - 1) % size for i in range(n)] last_samples = [buffer[i] for i in indices] avg = sum(last_samples) / n print(round(avg, 2))
Remember to wrap indices using modulo and sum the correct samples.
Write position 2 means last written samples are at indices 1, 0, and 4: values 7, 4, and 5. Average is (7+4+5)/3 = 5.33.
