blob: dd40bc4ee9df196b8dbe545f54de4d40cbff3551 [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}}
Fred Drakeb91e9341998-07-23 17:59:49 +00006\declaremodule{standard}{bisect}
7
Fred Drakeedf6b1f1998-07-27 22:16:46 +00008\modulesynopsis{Array bisection algorithms for binary searching.}
Fred Drakeb91e9341998-07-23 17:59:49 +00009
Fred Drakeca6b4fe1998-04-28 18:28:21 +000010
11
12This module provides support for maintaining a list in sorted order
13without having to sort the list after each insertion. For long lists
14of items with expensive comparison operations, this can be an
15improvement over the more common approach. The module is called
16\module{bisect} because it uses a basic bisection algorithm to do its
17work. The source code may be used a useful reference for a working
18example of the algorithm (i.e., the boundary conditions are already
19right!).
20
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}