Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find an index at which a new item can be inserted into sorted list and keep it sorted?

a = 132  b = [0, 10, 30, 60, 100, 150, 210, 280, 340, 480, 530] 

I want to know that a should be in the 6th position in ordered list b.

What's the most pythonic way to do so?

like image 978
est Avatar asked Jul 02 '12 09:07

est


People also ask

How can we search for an element in a sorted list?

The idea is to find the pivot point, divide the array into two sub-arrays and perform a binary search. For a sorted (in increasing order) and rotated array, the pivot element is the only element for which the next element to it is smaller than it. Using binary search based on the above idea, pivot can be found.

Which method can be used to place an item at a specific index in a list in Python?

To insert or add an item at specific position or index in a list, you can use insert() method of List class.

In which search array should be in sorted form?

Binary search works on sorted arrays. Binary search begins by comparing an element in the middle of the array with the target value.


1 Answers

bisect is a module in the Python Standard Library that is perfect for this task. The function bisect in the module bisect will give you the index of the insertion point for the value.

Let me give a code example for bisect

from bisect import bisect a = 132 b = [0, 10, 30, 60, 100, 150, 210, 280, 340, 480, 530] print(bisect(b, a)) 

The result will be 5 because the list is 0-based, so in fact it is the 6th position.

What you can do know is to use the result for an insert.

index = bisect(b, a) b.insert(index, a) 

or without the intermediate variable

b.insert(bisect(b, a), a) 

Now b will be [0, 10, 30, 60, 100, 132, 150, 210, 280, 340, 480, 530].

like image 131
Matthias Avatar answered Sep 19 '22 15:09

Matthias