|
| 1 | +% LaTeX produced by Fred L. Drake, Jr. <[email protected]>, with an |
| 2 | +% example based on the PyModules FAQ entry by Aaron Watters |
| 3 | + |
| 4 | + |
| 5 | +\section{Standard Module \module{bisect}} |
| 6 | +\stmodindex{bisect} |
| 7 | +\label{module-bisect} |
| 8 | + |
| 9 | + |
| 10 | +This module provides support for maintaining a list in sorted order |
| 11 | +without having to sort the list after each insertion. For long lists |
| 12 | +of items with expensive comparison operations, this can be an |
| 13 | +improvement over the more common approach. The module is called |
| 14 | +\module{bisect} because it uses a basic bisection algorithm to do its |
| 15 | +work. The source code may be used a useful reference for a working |
| 16 | +example of the algorithm (i.e., the boundary conditions are already |
| 17 | +right!). |
| 18 | + |
| 19 | +The following functions are provided: |
| 20 | + |
| 21 | +\begin{funcdesc}{bisect}{list, item\optional{, lo\optional{, hi}}} |
| 22 | +Locate the proper insertion point for \var{item} in \var{list} to |
| 23 | +maintain sorted order. The parameters \var{lo} and \var{hi} may be |
| 24 | +used to specify a subset of the list which should be considered. The |
| 25 | +return value is suitable for use as the first parameter to |
| 26 | +\code{\var{list}.insert()}. |
| 27 | +\end{funcdesc} |
| 28 | + |
| 29 | +\begin{funcdesc}{insort}{list, item\optional{, lo\optional{, hi}}} |
| 30 | +Insert \var{item} in \var{list} in sorted order. This is equivalent |
| 31 | +to \code{\var{list}.insert(bisect.bisect(\var{list}, \var{item}, |
| 32 | +\var{lo}, \var{hi}), \var{item})}. |
| 33 | +\end{funcdesc} |
| 34 | + |
| 35 | + |
| 36 | +\subsection{Example} |
| 37 | +\nodename{bisect-example} |
| 38 | + |
| 39 | +The \function{bisect()} function is generally useful for categorizing |
| 40 | +numeric data. This example uses \function{bisect()} to look up a |
| 41 | +letter grade for an exam total (say) based on a set of ordered numeric |
| 42 | +breakpoints: 85 and up is an `A', 75..84 is a `B', etc. |
| 43 | + |
| 44 | +\begin{verbatim} |
| 45 | +>>> grades = "FEDCBA" |
| 46 | +>>> breakpoints = [30, 44, 66, 75, 85] |
| 47 | +>>> from bisect import bisect |
| 48 | +>>> def grade(total): |
| 49 | +... return grades[bisect(breakpoints, total)] |
| 50 | +... |
| 51 | +>>> grade(66) |
| 52 | +'C' |
| 53 | +>>> map(grade, [33, 99, 77, 44, 12, 88]) |
| 54 | +['E', 'A', 'B', 'D', 'F', 'A'] |
| 55 | +\end{verbatim} |
0 commit comments