15/32
Part 4 of 6 · Deques and rate limitsLearn and do

On a stream, a deque and a Counter hold the last k keys

With a deque, the fixed window runs on a stream. Append the new key. Once the deque holds more than k, popleft() hands you the key that's leaving, so you can take it off the Counter:

from collections import Counter, deque

# keys can be a generator
def distinct_per_window_stream(keys, k):
    window, counts = deque(), Counter()
    for key in keys:
        window.append(key)
        counts[key] += 1
        if len(window) > k:
            old = window.popleft()
            counts[old] -= 1
            if counts[old] == 0:
                del counts[old]
        if len(window) == k:
            yield len(counts)

stream = (key for key in ["ana", "bo", "ana", "cy", "bo", "bo"])
print(list(distinct_per_window_stream(stream, 3)))
[2, 3, 3, 2]

That's the same answer as the list version you wrote earlier in this lesson. Memory is O(k), however long the stream runs.

A deque can also cap its own length. Once a capped deque is full, each append drops an item from the other end:

recent = deque(maxlen=3)
for key in ["ana", "bo", "cy", "dee"]:
    recent.append(key)
print(recent)
deque(['bo', 'cy', 'dee'], maxlen=3)

That's handy for showing the last k requests on a screen. For the Counter it's a trap: the deque drops ana without telling you, so the Counter never hears that ana left. Read window[0] before you append, or use popleft() as above.

The editor holds distinct_per_window_stream rewritten with deque(maxlen=k), and it falls into that trap. Fix it so the Counter hears about each key that leaves.