5.10.1 Examples

The bisect() function is generally useful for categorizing numeric data. This example uses bisect() to look up a letter grade for an exam total (say) based on a set of ordered numeric breakpoints: 85 and up is an `A', 75..84 is a `B', etc.

>>> grades = "FEDCBA"
>>> breakpoints = [30, 44, 66, 75, 85]
>>> from bisect import bisect
>>> def grade(total):
...           return grades[bisect(breakpoints, total)]
>>> grade(66)
>>> map(grade, [33, 99, 77, 44, 12, 88])
['E', 'A', 'B', 'D', 'F', 'A']

The bisect module can be used with the Queue module to implement a priority queue (example courtesy of Fredrik Lundh):

import Queue, bisect

class PriorityQueue(Queue.Queue):
    def _put(self, item):
        bisect.insort(self.queue, item)

# usage
queue = PriorityQueue(0)
queue.put((2, "second"))
queue.put((1, "first"))
queue.put((3, "third"))
priority, value = queue.get()
See About this document... for information on suggesting changes.