Merge pull request #298 from nzjia/patch-1

fix IndexError when E. bigger than others
This commit is contained in:
wangzheng0822 2019-04-30 21:01:46 +08:00 committed by GitHub
commit 6dba4a3a80
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,5 +1,6 @@
"""
Author: Wenru
Fix: nzjia
"""
from typing import List
@ -16,7 +17,11 @@ def bsearch_left(nums: List[int], target: int) -> int:
low = mid + 1
else:
high = mid - 1
return low if nums[low] == target else -1
if low < len(nums) and nums[low] == target:
return low
else:
return -1
def bsearch_right(nums: List[int], target: int) -> int:
"""Binary search of the index of the last element
@ -30,7 +35,10 @@ def bsearch_right(nums: List[int], target: int) -> int:
low = mid + 1
else:
high = mid - 1
return high if nums[high] == target else -1
if high >= 0 and nums[high] == target:
return high
else:
return -1
def bsearch_left_not_less(nums: List[int], target: int) -> int:
@ -45,7 +53,10 @@ def bsearch_left_not_less(nums: List[int], target: int) -> int:
low = mid + 1
else:
high = mid - 1
return low if low < len(nums) else -1
if low < len(nums) and nums[low] >= target:
return low
else:
return -1
def bsearch_right_not_greater(nums: List[int], target: int) -> int:
"""Binary search of the index of the last element
@ -59,19 +70,26 @@ def bsearch_right_not_greater(nums: List[int], target: int) -> int:
low = mid + 1
else:
high = mid - 1
return high if high > 0 else -1
if high >= 0 and nums[high] <= target:
return high
else:
return -1
if __name__ == "__main__":
import bisect
a = [1, 1, 2, 3, 4, 6, 7, 7, 7, 7, 10, 22]
a = [0, 1, 1, 2, 3, 4, 5, 6, 6, 7, 8, 8, 10, 10, 10]
b = [11, 12, 12, 13, 14, 14, 15, 15]
print(bisect.bisect_left(a, 10) == bsearch_left(a, 10))
print(bisect.bisect_right(a, 10))
print(bisect.bisect_right(a, 6)-1 == bsearch_right(a, 6))
print(bisect.bisect_right(b, 14)-1 == bsearch_right(b, 14))
print(bsearch_left(a, 0) == -1)
print(bsearch_left(a, 7) == 6)
print(bsearch_left(a, 30) == -1)
print(bsearch_left_not_less(a, 11))
print(bsearch_right_not_greater(b, 12))
print(bsearch_right_not_greater(b, 10))
print(bsearch_right_not_greater(b, 17))
print(bsearch_right(a, 0) == -1)
print(bsearch_right(a, 7) == 9)
print(bsearch_right(a, 30) == -1)
print(bsearch_left_not_less(a, 0) == 0)
print(bsearch_left_not_less(a, 5) == 5)
print(bsearch_left_not_less(a, 30) == -1)
print(bsearch_right_not_greater(a, 0) == -1)
print(bsearch_right_not_greater(a, 6) == 5)
print(bsearch_right_not_greater(a, 30) == 11)