Movatterモバイル変換


[0]ホーム

URL:


Navigation

bisect — Array bisection algorithm

This module provides support for maintaining a list in sorted order withouthaving to sort the list after each insertion. For long lists of items withexpensive comparison operations, this can be an improvement over the more commonapproach. The module is calledbisect because it uses a basic bisectionalgorithm to do its work. The source code may be most useful as a workingexample of the algorithm (the boundary conditions are already right!).

The following functions are provided:

bisect.bisect_left(list,item[,lo[,hi]])

Locate the proper insertion point foritem inlist to maintain sorted order.The parameterslo andhi may be used to specify a subset of the list whichshould be considered; by default the entire list is used. Ifitem is alreadypresent inlist, the insertion point will be before (to the left of) anyexisting entries. The return value is suitable for use as the first parametertolist.insert(). This assumes thatlist is already sorted.

New in version 2.1.

bisect.bisect_right(list,item[,lo[,hi]])

Similar tobisect_left(), but returns an insertion point which comes after(to the right of) any existing entries ofitem inlist.

New in version 2.1.

bisect.bisect(...)
Alias forbisect_right().
bisect.insort_left(list,item[,lo[,hi]])

Insertitem inlist in sorted order. This is equivalent tolist.insert(bisect.bisect_left(list,item,lo,hi),item). This assumesthatlist is already sorted.

New in version 2.1.

bisect.insort_right(list,item[,lo[,hi]])

Similar toinsort_left(), but insertingitem inlist after anyexisting entries ofitem.

New in version 2.1.

bisect.insort(...)
Alias forinsort_right().

Examples

Thebisect() function is generally useful for categorizing numeric data.This example usesbisect() to look up a letter grade for an exam total(say) based on a set of ordered numeric breakpoints: 85 and up is an ‘A’, 75..84is a ‘B’, etc.

>>>grades="FEDCBA">>>breakpoints=[30,44,66,75,85]>>>frombisectimportbisect>>>defgrade(total):...returngrades[bisect(breakpoints,total)]...>>>grade(66)'C'>>>map(grade,[33,99,77,44,12,88])['E', 'A', 'B', 'D', 'F', 'A']

Table Of Contents

Previous topic

heapq — Heap queue algorithm

Next topic

array — Efficient arrays of numeric values

This Page

Quick search

Navigation

©Copyright 1990-2008, Python Software Foundation. Last updated on Oct 02, 2008. Created usingSphinx 0.5.

[8]ページ先頭

©2009-2026 Movatter.jp