From d0c8c828dc39dc35916abae67598f89e68203315 Mon Sep 17 00:00:00 2001 From: chenzhejia <36252498+nzjia@users.noreply.github.com> Date: Thu, 18 Apr 2019 16:16:39 +0800 Subject: [PATCH] fix IndexError when E. bigger than others --- python/16_bsearch/bsearch_variants.py | 48 ++++++++++++++++++--------- 1 file changed, 33 insertions(+), 15 deletions(-) diff --git a/python/16_bsearch/bsearch_variants.py b/python/16_bsearch/bsearch_variants.py index 1b0b444..0b69955 100644 --- a/python/16_bsearch/bsearch_variants.py +++ b/python/16_bsearch/bsearch_variants.py @@ -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)) \ No newline at end of file + 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)