# CS21: Counter

In class Nov 24

Implementing a Counter class

Write a class called Counter that keeps track of how often you see items.

The Counter class will store a list of lists such that each element of the list is an [item, count] pair (where the items are stored in sorted order). For example, the following list of lists counts how often the letters a-f were seen:

[['a', 5], ['b', 6], ['c', 1], ['d', 8], ['f', 2]]


Note that 'e' was never seen so it does not appear in the list.

The Counter class should have a constructor that takes no arguments and initializes the LoL to be empty.

It should also support the following methods:
• add(item): adds a new item to the LoL or updates the count of that item. For example, if we called add('a') with the above list, we would now have:
 [['a', 6], ['b', 6], ['c', 1], ['d', 8], ['f', 2]]

And if we called add('e')
 [['a', 6], ['b', 6], ['c', 1], ['d', 8], ['e', 1], ['f', 2]]

• getcount(item): returns the count of the item. If the item has not been seen yet, return 0
• mostfrequent(item): returns the [item, count] for the most frequent item
• ranked(): returns the list of items sorted by frequency
• clear(): empties the contents of the Counter
• __str__ to retusn a string representing the contents of the Counter

You will almost certainly want to write two other methods to help:

• find(item): returns the index of the item in the list, or -1 if it is not found. Try to use binary search here, but linear search is OK as a first attempt.
• insert(item): insert item into the list in sorted order with count 1. This will be useful when you try to add an item to the Counter that you haven't seen before.

When you're all done, write some tests to make sure that it works!