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
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With