cpython

cpython / Lib / bisect.py / Jump to Code definitions Function insort_right Function bisect_right Function insort_left Function bisect_left Code navigation index up-to-date

Go to file

  • TGo to file
  • Go to lineL
  • Go to definitionR
  • Copy path

  • Copy permalink

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.  Cannot retrieve contributors at this time

110 lines (89 sloc)

3.06 KB

Raw
Blame
Edit this fileE

Open in GitHub Desktop

  • Open with Desktop

  • View raw

  • Copy raw contents
    Copy raw contents
    Copy raw contents
    Copy raw contents
  • View blame

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Show hidden characters

“””Bisection algorithms.”””
definsort_right(a, x, lo=0, hi=None, *, key=None):
“””Insert item x in list a, and keep it sorted assuming a is sorted.
If x is already in a, insert it to the right of the rightmost x.
Optional args lo (default 0) and hi (default len(a)) bound the
slice of a to be searched.
“””
ifkeyisNone:
lo=bisect_right(a, x, lo, hi)
else:
lo=bisect_right(a, key(x), lo, hi, key=key)
a.insert(lo, x)
defbisect_right(a, x, lo=0, hi=None, *, key=None):
“””Return the index where to insert item x in list a, assuming a is sorted.
The return value i is such that all e in a[:i] have e <= x, and all e in
a[i:] have e > x. So if x already appears in the list, a.insert(i, x) will
insert just after the rightmost x already there.
Optional args lo (default 0) and hi (default len(a)) bound the
slice of a to be searched.
“””
iflo<0:
raiseValueError(‘lo must be non-negative’)
ifhiisNone:
hi=len(a)
# Note, the comparison uses “<" to match the
# __lt__() logic in list.sort() and in heapq.
ifkeyisNone:
whilelo<>
mid= (lo+hi) //2
ifx<>
hi=mid
else:
lo=mid+1
else:
whilelo<>
mid= (lo+hi) //2
ifx<>
hi=mid
else:
lo=mid+1
returnlo
definsort_left(a, x, lo=0, hi=None, *, key=None):
“””Insert item x in list a, and keep it sorted assuming a is sorted.
If x is already in a, insert it to the left of the leftmost x.
Optional args lo (default 0) and hi (default len(a)) bound the
slice of a to be searched.
“””
ifkeyisNone:
lo=bisect_left(a, x, lo, hi)
else:
lo=bisect_left(a, key(x), lo, hi, key=key)
a.insert(lo, x)
defbisect_left(a, x, lo=0, hi=None, *, key=None):
“””Return the index where to insert item x in list a, assuming a is sorted.
The return value i is such that all e in a[:i] have e < x, and all e in
a[i:] have e >= x. So if x already appears in the list, a.insert(i, x) will
insert just before the leftmost x already there.
Optional args lo (default 0) and hi (default len(a)) bound the
slice of a to be searched.
“””
iflo<0:
raiseValueError(‘lo must be non-negative’)
ifhiisNone:
hi=len(a)
# Note, the comparison uses “<" to match the
# __lt__() logic in list.sort() and in heapq.
ifkeyisNone:
whilelo<>
mid= (lo+hi) //2
ifa[mid] <>
lo=mid+1
else:
hi=mid
else:
whilelo<>
mid= (lo+hi) //2
ifkey(a[mid]) <>
lo=mid+1
else:
hi=mid
returnlo
# Overwrite above definitions with a fast C implementation
try:
from_bisectimport*
exceptImportError:
pass
# Create aliases
bisect=bisect_right
insort=insort_right
  • Copy lines
  • Copy permalink
  • View git blame
  • Reference in new issue

Go

Recommended from Medium

Deepak

Deepak

Must Read:

  • How to Convert String to Lowercase in
  • How to Calculate Square Root
  • User Input | Input () Function | Keyboard Input
  • Best Book to Learn Python

Python3

# Python code to demonstrate the working of# bisect(), bisect_left() and bisect_right()  # importing “bisect” for bisection operationsimportbisect  # initializing listli =[1, 3, 4, 4, 4, 6, 7]  # using bisect() to find index to insert new element# returns 5 ( right most possible index )print(“Rightmost index to insert, so list remains sorted is : “,       end=””)print(bisect.bisect(li, 4))  # using bisect_left() to find index to insert new element# returns 2 ( left most possible index )print(“Leftmost index to insert, so list remains sorted is : “,        end=””)print(bisect.bisect_left(li, 4))  # using bisect_right() to find index to insert new element# returns 4 ( right most possible index )print(“Rightmost index to insert, so list remains sorted is : “,       end=””)print(bisect.bisect_right(li, 4, 0, 4))

Output:

The rightmost index to insert, so list remains sorted is : 5
The leftmost index to insert, so list remains sorted is : 2
The rightmost index to insert, so list remains sorted is : 4

Time Complexity:

O(log(n)) -> Bisect method works on the concept of binary search

4. insort(list, num, beg, end) :- This function returns the sorted list after inserting number in appropriate position, if the element is already present in the list, the element is inserted at the rightmost possible position. 

This function takes 4 arguments, list which has to be worked with, number to insert, starting position in list to consider, ending position which has to be considered. 

5. insort_left(list, num, beg, end) :- This function returns the sorted list after inserting number in appropriate position, if the element is already present in the list, the element is inserted at the leftmost possible position. 

This function takes 4 arguments, list which has to be worked with, number to insert, starting position in list to consider, ending position which has to be considered. 

6. insort_right(list, num, beg, end) :- This function works similar to the “insort()” as mentioned above. 

What Is Application Migration?


Nicholas Teague

Nicholas Teague

in

Automunge

Some More Examples- 

  • Let us see how can bisect() help us in strings- 

Suppose you have a list of student names in sorted order. Now, a new student named ‘Manish’ takes admission. Now let us see how we can add his name keeping the list sorted.

names=[‘Ashwini’,’Bulbul’,’Chetan’,’Naman’,’Zubair’] new=’Manish’
bisect.insort(names,new)
print(names)
Output-
[‘Ashwini’, ‘Bulbul’, ‘Chetan’, ‘Manish’, ‘Naman’, ‘Zubair’] 

  • Let, suppose we want to add a list of marks in our marks list.  

marks=[21,30,31,33,36,40,43,44,48,50] newlist=[32,48,29] for i in newlist:
bisect.insort(marks,i)
print(marks)
Output-
[21, 29, 30, 31, 32, 33, 36, 40, 43, 44, 48, 48, 50] 

Limitations of Python Bisect()- 

  • We need elements in sorted order. To solve this problem, we can use the python sort() function. 

marks=[21,30,43,12,29,50,48] marks.sort()
newlist=[32,48,29] for i in newlist:
bisect.insort(marks,i)
print(marks)
Output-
[12,21,29,29,30,32,43,48,48,50]

  • If the list is in descending order, we first need to convert it to ascending order. 

marks=[50,49,48,47,46] marks.sort()
newlist=[32,48,29] for i in newlist:
bisect.insort(marks,i)
print(marks[::-1])
Output-
[50, 49, 48, 48, 47, 46, 32, 29] 

bisect.bisect_right() Overview

It is used to return the rightmost insertion point of a number x inside a sorted list. If x is already present in the list, then new x will be inserted in the rightmost position among all x in the list.

Syntax

bisect_right(arr, x, lo = 0, hi = len(a))

Parameters

arrThe input list
xThe element whose insertion point we are locating.
loIt helps to specify the starting index of a subset of a list. The default value is 0.
hiIt helps to specify the ending index of a subset of a list. The default value is len(arr).

Return

It returns an insertion point that partitions the array into two halves: the first with all values <= x and the second with all values > x.

bisect_right(a, x, lo=0, hi=None)

This function works the same as bisect_left but in the event that x value already appears in the a list , the index i would be just after the rightmost x value already there. Let us see an example.

4-bisect_right function

Notice that x value (4) rightmost that appears in the list is at index 4 therefore, the index just after would be the 5. The lo and hi parameters work like in the bisect_left function.

Footer

© 2022 GitHub, Inc.

insort_right(a, x, lo=0, hi=None)

This function works the same way as insort_left, except that it uses the bisect_right function to find where the x value needs to be inserted.

Let us see an example:

6- insort_right function

The previous snippet was used in section bisect_right, notice that the same result was obtained.

This is the simplest way to use the functions of the Bisect Module. It is important to mention that the time complexity of bisect_left and bisect_right is O(log(n)) since their implementation uses Binary Search Algorithm. The time complexity of the insort_right and insort_left functions depends on the complexity of the insert method of the list class which is O(n).

In all of the examples were used lists of integers but you can use a list of floats or even strings. Perhaps you have wondered What if I use a tuple or a string? Good question!. Well, you can use bisect_left and bisect_right in tuples and strings without any problem but if you try to use the insort_left and insort_right on these objects you are getting an error. And why? This happens because the tuples and the strings are immutable objects and these types of objects do not have implemented the insert method which modifies one mutable object as a list in-place.

bisect_right and insort_right have aliases, so bisect_right can be called simply bisect and insort_right as insort.

Finally, Find out what happens when you try to use these functions on a list ordered in decreasing order or even on an unsorted list. You will find out easily!

Remember not to reinvent the wheel!

If you have any comments about this post, please let me know :).

References

  • bisect — Array bisection algorithm

insort_left(a, x, lo=0, hi=None)

In the previous snippets was used the insert method of the object list to insert the x value in the a list by using the index i returned by the bisect_left function, well, the insort_left function does this for us, so it calls the bisect_left function and then the insert method.

The lo and hi parameters in this function behave as in the previous functions. There is nothing new here.

Let us see the following example:

5-insort_left function

The snippet above corresponds to the third snippet (2-insert x value) presented as an example in the explanation of the bisect_left function, notice that the result is the same.

Applications of bisect_left()

Find the first occurrence of an element

from bisect import bisect_left

def binary_search(a, x):
i = bisect_left(a, x)
if i != len(a) and a[i] == x:
return i
else:
return -1

a = [1, 2, 3, 3, 3] x = int(3)
res = binary_search(a, x)
if res == -1:
print(“Element not Found”)
else:
print(“First occurrence of”, x, “is at index”, res)

Output:

First occurrence of 3 is at index 2

Findthe greatest value smaller than x

from bisect import bisect_left

def binary_search(a, x):
i = bisect_left(a, x)
if i:
return (i-1)
else:
return -1

# Driver code
a = [1, 2, 4, 4, 8] x = int(7)
res = binary_search(a, x)
if res == -1:
print(“There is no value smaller than”, x)
else:
print(“Largest value smaller than”, x, ” is at index”, res)

Output:

Largest value smaller than 7 is at index 3

Big Data? what’s that?


Shaheer Shahid Malik

Shaheer Shahid Malik

in

CodeX

Applications of bisect_right()

More from Analytics Vidhya

Analytics Vidhya is a community of Analytics and Data Science professionals. We are building the next-gen data science ecosystem https://www.analyticsvidhya.com

Analytics VidhyaRead more from

Program to find the index without python bisect module- 

Let’s make a program working the same as python bisect.bisect(). 

numbers=[10,12,14,17,19.2,22,23] x=17
for i in range(len(numbers)):
if numbers[i] < x: pass #For bisect.left() remove the below elif statement elif numbers[i] == x: pass else: print(i) break Output 4

This much of code we have to write when we want to search for index without using the bisect(). Also, this program takes much more time to implement than bisect() when we have lots and lots of data. 

Now let’s program for insort()- 

numbers=[10,12,14,17,19.2,22,23] x=17
for i in range(len(numbers)):
if numbers[i] < x: pass #For insort.left() remove the below elif statement elif numbers[i] == x: pass else: numbers[i]=x break Output- [10,12,14,17,17,19.2,22,23] 

  Now you can think about how easy the python bisect module makes it for us. 

Источники

  • https://github.com/python/cpython/blob/main/Lib/bisect.py
  • https://medium.com/analytics-vidhya/bisect-module-in-python-6b78f8c37beb
  • https://www.pythonpool.com/python-bisect/
  • https://www.geeksforgeeks.org/bisect-algorithm-functions-in-python/
  • https://www.delftstack.com/howto/python/python-bisect/
[свернуть]
Решите Вашу проблему!


×
Adblock
detector