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?
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.
To insert or add an item at specific position or index in a list, you can use insert() method of List class.
Binary search works on sorted arrays. Binary search begins by comparing an element in the middle of the array with the target value.
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]
.
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