blob: e36cf0e7959b2f185cb5a4df883374bb606ae743 [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
Fred Draked8a41e61999-02-19 17:54:10 +000018work. The source code may be most useful as a working example of the
19algorithm (i.e., the boundary conditions are already right!).
Fred Drakeca6b4fe1998-04-28 18:28:21 +000020
21The following functions are provided:
22
23\begin{funcdesc}{bisect}{list, item\optional{, lo\optional{, hi}}}
24Locate the proper insertion point for \var{item} in \var{list} to
25maintain sorted order. The parameters \var{lo} and \var{hi} may be
26used to specify a subset of the list which should be considered. The
27return value is suitable for use as the first parameter to
28\code{\var{list}.insert()}.
29\end{funcdesc}
30
31\begin{funcdesc}{insort}{list, item\optional{, lo\optional{, hi}}}
32Insert \var{item} in \var{list} in sorted order. This is equivalent
33to \code{\var{list}.insert(bisect.bisect(\var{list}, \var{item},
34\var{lo}, \var{hi}), \var{item})}.
35\end{funcdesc}
36
37
38\subsection{Example}
39\nodename{bisect-example}
40
41The \function{bisect()} function is generally useful for categorizing
42numeric data. This example uses \function{bisect()} to look up a
43letter grade for an exam total (say) based on a set of ordered numeric
44breakpoints: 85 and up is an `A', 75..84 is a `B', etc.
45
46\begin{verbatim}
47>>> grades = "FEDCBA"
48>>> breakpoints = [30, 44, 66, 75, 85]
49>>> from bisect import bisect
50>>> def grade(total):
51... return grades[bisect(breakpoints, total)]
52...
53>>> grade(66)
54'C'
55>>> map(grade, [33, 99, 77, 44, 12, 88])
56['E', 'A', 'B', 'D', 'F', 'A']
57\end{verbatim}