blob: 246d6c7730a58acfa0d7c5ff5a2c28e8ae83bdd4 [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
Fred Drake295da241998-08-10 19:42:37 +00005\section{\module{bisect} ---
6 Array bisection algorithms for binary searching.}
Fred Drakeb91e9341998-07-23 17:59:49 +00007\declaremodule{standard}{bisect}
8
Fred Drakeedf6b1f1998-07-27 22:16:46 +00009\modulesynopsis{Array bisection algorithms for binary searching.}
Fred Drakeb91e9341998-07-23 17:59:49 +000010
Fred Drakeca6b4fe1998-04-28 18:28:21 +000011
12
13This module provides support for maintaining a list in sorted order
14without having to sort the list after each insertion. For long lists
15of items with expensive comparison operations, this can be an
16improvement over the more common approach. The module is called
17\module{bisect} because it uses a basic bisection algorithm to do its
18work. The source code may be used a useful reference for a working
19example of the algorithm (i.e., the boundary conditions are already
20right!).
21
22The following functions are provided:
23
24\begin{funcdesc}{bisect}{list, item\optional{, lo\optional{, hi}}}
25Locate the proper insertion point for \var{item} in \var{list} to
26maintain sorted order. The parameters \var{lo} and \var{hi} may be
27used to specify a subset of the list which should be considered. The
28return value is suitable for use as the first parameter to
29\code{\var{list}.insert()}.
30\end{funcdesc}
31
32\begin{funcdesc}{insort}{list, item\optional{, lo\optional{, hi}}}
33Insert \var{item} in \var{list} in sorted order. This is equivalent
34to \code{\var{list}.insert(bisect.bisect(\var{list}, \var{item},
35\var{lo}, \var{hi}), \var{item})}.
36\end{funcdesc}
37
38
39\subsection{Example}
40\nodename{bisect-example}
41
42The \function{bisect()} function is generally useful for categorizing
43numeric data. This example uses \function{bisect()} to look up a
44letter grade for an exam total (say) based on a set of ordered numeric
45breakpoints: 85 and up is an `A', 75..84 is a `B', etc.
46
47\begin{verbatim}
48>>> grades = "FEDCBA"
49>>> breakpoints = [30, 44, 66, 75, 85]
50>>> from bisect import bisect
51>>> def grade(total):
52... return grades[bisect(breakpoints, total)]
53...
54>>> grade(66)
55'C'
56>>> map(grade, [33, 99, 77, 44, 12, 88])
57['E', 'A', 'B', 'D', 'F', 'A']
58\end{verbatim}