Quantcast
Channel: CodeSection,代码区,Python开发技术文章_教程 - CodeSec
Viewing all articles
Browse latest Browse all 9596

Search Insert Position & Python bisect

$
0
0

I happened to see the usage of python bisect package in a project today, so I write these words to deepen impression on this Array bisection algorithm .

Problem in LeetCode

35. Search Insert Position

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates in the array.

Here are few examples.

[1,3,5,6] , 5 → 2 [1,3,5,6] , 2 → 1 [1,3,5,6] , 7 → 4 [1,3,5,6] , 0 → 0 Exmaple Solution

Find code on Github

class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
low = 0
high = len(nums)
while low < high:
mid = (low + high) / 2
if target < nums[mid]:
high = mid
elif target == nums[mid]:
return mid
else:
low = mid + 1
return low Python bisect ― Array bisection algorithm

https://docs.python.org/2/library/bisect.html

This module provides support for maintaining a list in sorted order without having to sort the list after each insertion. For long lists of items with expensive comparison operations, this can be an improvement over the more common approach. The module is called bisect because it uses a basic bisection algorithm to do its work. The source code may be most useful as a working example of the algorithm (the boundary conditions are already right!).

Source code Lib/bisect.py

def bisect_right(a, x, lo=0, hi=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(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.
"""
if lo < 0:
raise ValueError('lo must be non-negative')
if hi is None:
hi = len(a)
while lo < hi:
mid = (lo+hi)//2
if x < a[mid]: hi = mid
else: lo = mid+1
return lo

enjoy it!

_(:з」∠)_


Viewing all articles
Browse latest Browse all 9596

Trending Articles