Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bisect a Python List and finding the Index

When I use the bisect_left() function, why do I not get the index of the element, but instead index + 1?

import bisect

t3 = ['carver', 'carvers', 'carves', 'carving', 'carvings']
print bisect.bisect(t3, 'carves')    # 3
print bisect.bisect(t3, 'carving')   # 4
print bisect.bisect(t3, 'carver')    # 1
like image 253
Nyxynyx Avatar asked Oct 04 '13 13:10

Nyxynyx


People also ask

What does bisect return Python?

bisect(list, num, beg, end) :- This function returns the position in the sorted list, where the number passed in argument can be placed so as to maintain the resultant list in sorted order. If the element is already present in the list, the right most position where element has to be inserted is returned.

Does Python bisect use binary search?

Practical Data Science using PythonThe bisect is used for binary search. The binary search technique is used to find elements in sorted list. The bisect is one library function.


1 Answers

bisect.bisect() is a shorter name for bisect.bisect_right(), not bisect.bisect_left().

You'll need to use the full name, bisect.bisect_left(), instead:

>>> import bisect
>>> t3 = ['carver', 'carvers', 'carves', 'carving', 'carvings']
>>> bisect.bisect(t3, 'carves')
3
>>> bisect.bisect_left(t3, 'carves')
2
>>> bisect.bisect == bisect.bisect_right
True
>>> bisect.bisect == bisect.bisect_left
False
like image 160
Martijn Pieters Avatar answered Oct 07 '22 13:10

Martijn Pieters