Explore the Python module bisect to search a sorted list and insert elements in the proper location in a sorted list.
Searching a list with bisect
''' bisect_search.py
If a list is long and sorted, then a binary search is faster
than a list index() search.
works with Python27 and Python32 HiHe
'''
import bisect
def linear_search(names, search):
"""
a standard linear search
"""
ix = names.index(search)
sf = "Linear search for {}, found it at index {}"
print(sf.format(search, ix))
def bisect_search(names, search):
"""
search using bisect()
no-match gives closest index (no index error)
"""
ix = bisect.bisect(names, search) - 1
sf = "Bisect search for {}, found it at index {}"
# this will trap the no-match situation
if names[ix] == search:
print(sf.format(search, ix))
else:
print("{} not found!".format(search))
names = [
'Pam', 'Zoe', 'Dee', 'Eva', 'Gin', 'Ivy', 'Kay', 'Amy', 'Moe'
]
# bisect search needs a sorted list
names.sort()
print(names)
print('-'*70)
search = 'Kay'
linear_search(names, search)
print('-'*70)
bisect_search(names, search)
print('-'*70)
# search for a name not in the list
search = 'Lisa'
bisect_search(names, search)
print('-'*70)
# you can insert a name into the sorted name list at the proper spot
new_name = 'Mae'
bisect.insort_left(names, new_name)
print(names) # testing
''' output >>>
['Amy', 'Dee', 'Eva', 'Gin', 'Ivy', 'Kay', 'Moe', 'Pam', 'Zoe']
----------------------------------------------------------------------
Linear search for Kay, found it at index 5
----------------------------------------------------------------------
Bisect search for Kay, found it at index 5
----------------------------------------------------------------------
Lisa not found!
----------------------------------------------------------------------
['Amy', 'Dee', 'Eva', 'Gin', 'Ivy', 'Kay', 'Mae', 'Moe', 'Pam', 'Zoe']
'''
TrustyTony 888 ex-Moderator Team Colleague Featured Poster
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.