blob: 81cb550ca729eb7264684e36616d3a62ac4d98da [file] [log] [blame]
Fred Drakeca6b4fe1998-04-28 18:28:21 +00001% LaTeX produced by Fred L. Drake, Jr. <fdrake@acm.org>, with an
2% example based on the PyModules FAQ entry by Aaron Watters
3% <arw@pythonpros.com>.
4
5\section{Standard Module \module{bisect}}
6\stmodindex{bisect}
7\label{module-bisect}
8
9
10This module provides support for maintaining a list in sorted order
11without having to sort the list after each insertion. For long lists
12of items with expensive comparison operations, this can be an
13improvement over the more common approach. The module is called
14\module{bisect} because it uses a basic bisection algorithm to do its
15work. The source code may be used a useful reference for a working
16example of the algorithm (i.e., the boundary conditions are already
17right!).
18
19The following functions are provided:
20
21\begin{funcdesc}{bisect}{list, item\optional{, lo\optional{, hi}}}
22Locate the proper insertion point for \var{item} in \var{list} to
23maintain sorted order. The parameters \var{lo} and \var{hi} may be
24used to specify a subset of the list which should be considered. The
25return 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}}}
30Insert \var{item} in \var{list} in sorted order. This is equivalent
31to \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
39The \function{bisect()} function is generally useful for categorizing
40numeric data. This example uses \function{bisect()} to look up a
41letter grade for an exam total (say) based on a set of ordered numeric
42breakpoints: 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}