A cache that remembers tags already counted

Fill in the blanks · Medium · §11.6 The math helper evolves

This class counts how many posts have a given tag. It remembers each tag it has counted in the dictionary cache, and when it is asked about the same tag again, it returns the result right away without scanning the posts. scans counts how many times it has scanned the posts. Fill in the three blanks.

Code with blanks

class TagCounter:
    def __init__(self, posts):
        self.posts = posts
        self.cache = {}
        self.scans = 0

    def count(self, tag):
        if tag in ____:
            return ____
        self.scans += 1
        n = 0
        for tags in self.posts:
            if tag in tags:
                n += 1
        ____ = n
        return n

posts = [
    ["cat", "cafe"],
    ["dog"],
    ["cat"],
    ["cafe", "dog", "cat"],
]
tc = TagCounter(posts)
print(tc.count("cat"), tc.count("dog"), tc.count("cat"), tc.count("bird"))
print(tc.scans, tc.cache)

Solve this problem in your browser

Python runs in your browser and checks your answer right away. Hints and the answer are on the problem page.