blob: 555e3a7706baa1e0c6b72a803d7839491bf69bb6 [file] [log] [blame]
Fred Drake295da241998-08-10 19:42:37 +00001\section{\module{bisect} ---
Fred Drakebbac4321999-02-20 00:14:17 +00002 Array bisection algorithm}
3
Fred Drakeb91e9341998-07-23 17:59:49 +00004\declaremodule{standard}{bisect}
Fred Drakeedf6b1f1998-07-27 22:16:46 +00005\modulesynopsis{Array bisection algorithms for binary searching.}
Fred Drake38e5d272000-04-03 20:13:55 +00006\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>.
Fred Drakeb91e9341998-07-23 17:59:49 +000010
Fred Drakeca6b4fe1998-04-28 18:28:21 +000011
Fred Drakeca6b4fe1998-04-28 18:28:21 +000012This 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
Fred Draked8a41e61999-02-19 17:54:10 +000017work. The source code may be most useful as a working example of the
18algorithm (i.e., the boundary conditions are already right!).
Fred Drakeca6b4fe1998-04-28 18:28:21 +000019
20The following functions are provided:
21
22\begin{funcdesc}{bisect}{list, item\optional{, lo\optional{, hi}}}
23Locate the proper insertion point for \var{item} in \var{list} to
24maintain sorted order. The parameters \var{lo} and \var{hi} may be
25used to specify a subset of the list which should be considered. The
26return value is suitable for use as the first parameter to
27\code{\var{list}.insert()}.
28\end{funcdesc}
29
30\begin{funcdesc}{insort}{list, item\optional{, lo\optional{, hi}}}
31Insert \var{item} in \var{list} in sorted order. This is equivalent
32to \code{\var{list}.insert(bisect.bisect(\var{list}, \var{item},
33\var{lo}, \var{hi}), \var{item})}.
34\end{funcdesc}
35
36
37\subsection{Example}
38\nodename{bisect-example}
39
40The \function{bisect()} function is generally useful for categorizing
41numeric data. This example uses \function{bisect()} to look up a
42letter grade for an exam total (say) based on a set of ordered numeric
43breakpoints: 85 and up is an `A', 75..84 is a `B', etc.
44
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}