*Credit: John Jensen, Fred Bremmer, Nick
Coghlan*

You need to count the occurrences of various items and present the items in order of their number of occurrences—for example, to produce a histogram.

A histogram, apart from graphical issues, is based on
counting the occurrences of items (easy to do with a Python list or
dictionary) and then sorting the keys or indices in an order based on
corresponding values. Here is a subclass of `dict`

that adds two methods for the
purpose:

class hist(dict): def add(self, item, increment=1): ''' add 'increment' to the entry for 'item' ''' self[item] = increment + self.get(item, 0) def counts(self, reverse=False): ''' return list of keys sorted by corresponding values ''' aux = [ (self[k], k) for k in self ] aux.sort( ) if reverse: aux.reverse( ) return [k for v, k in aux]

If the items you're counting are best modeled by small integers in a compact range, so that you want to keep item counts in a list, the solution is quite similar:

class hist1(list): def _ _init_ _(self, n): ''' initialize this list to count occurrences of n distinct items ''' list._ _init_ _(self, n*[0]) def add(self, item, increment=1): ''' add 'increment' to the entry for 'item' ''' self[item] += increment def counts(self, reverse=False): ''' return list of indices sorted by corresponding values ''' aux = [ (v, k) for k, v in enumerate(self) ] aux.sort( ) if reverse: aux.reverse( ) return [k for v, k in aux] ...

Start Free Trial

No credit card required