Add forgotten initialization. Fixes bug #120994, "Traceback with
[python/dscho.git] / Doc / lib / libbisect.tex
blob555e3a7706baa1e0c6b72a803d7839491bf69bb6
1 \section{\module{bisect} ---
2 Array bisection algorithm}
4 \declaremodule{standard}{bisect}
5 \modulesynopsis{Array bisection algorithms for binary searching.}
6 \sectionauthor{Fred L. Drake, Jr.}{fdrake@acm.org}
7 % LaTeX produced by Fred L. Drake, Jr. <fdrake@acm.org>, with an
8 % example based on the PyModules FAQ entry by Aaron Watters
9 % <arw@pythonpros.com>.
12 This module provides support for maintaining a list in sorted order
13 without having to sort the list after each insertion. For long lists
14 of items with expensive comparison operations, this can be an
15 improvement over the more common approach. The module is called
16 \module{bisect} because it uses a basic bisection algorithm to do its
17 work. The source code may be most useful as a working example of the
18 algorithm (i.e., the boundary conditions are already right!).
20 The following functions are provided:
22 \begin{funcdesc}{bisect}{list, item\optional{, lo\optional{, hi}}}
23 Locate the proper insertion point for \var{item} in \var{list} to
24 maintain sorted order. The parameters \var{lo} and \var{hi} may be
25 used to specify a subset of the list which should be considered. The
26 return value is suitable for use as the first parameter to
27 \code{\var{list}.insert()}.
28 \end{funcdesc}
30 \begin{funcdesc}{insort}{list, item\optional{, lo\optional{, hi}}}
31 Insert \var{item} in \var{list} in sorted order. This is equivalent
32 to \code{\var{list}.insert(bisect.bisect(\var{list}, \var{item},
33 \var{lo}, \var{hi}), \var{item})}.
34 \end{funcdesc}
37 \subsection{Example}
38 \nodename{bisect-example}
40 The \function{bisect()} function is generally useful for categorizing
41 numeric data. This example uses \function{bisect()} to look up a
42 letter grade for an exam total (say) based on a set of ordered numeric
43 breakpoints: 85 and up is an `A', 75..84 is a `B', etc.
45 \begin{verbatim}
46 >>> grades = "FEDCBA"
47 >>> breakpoints = [30, 44, 66, 75, 85]
48 >>> from bisect import bisect
49 >>> def grade(total):
50 ... return grades[bisect(breakpoints, total)]
51 ...
52 >>> grade(66)
53 'C'
54 >>> map(grade, [33, 99, 77, 44, 12, 88])
55 ['E', 'A', 'B', 'D', 'F', 'A']
56 \end{verbatim}