Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add test for bsearch_variants.py #527

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 21 additions & 3 deletions python/16_bsearch/bsearch_variants.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

from typing import List


def bsearch_left(nums: List[int], target: int) -> int:
"""Binary search of the index of the first element
equal to a given target in the ascending sorted array.
Expand Down Expand Up @@ -58,6 +59,7 @@ def bsearch_left_not_less(nums: List[int], target: int) -> int:
else:
return -1


def bsearch_right_not_greater(nums: List[int], target: int) -> int:
"""Binary search of the index of the last element
not greater than a given target in the ascending sorted array.
Expand All @@ -75,6 +77,24 @@ def bsearch_right_not_greater(nums: List[int], target: int) -> int:
else:
return -1


def test_bsearch_left_not_less():
a = bsearch_left_not_less([1, 2, 5], 1)
assert a == 0
a = bsearch_left_not_less([1, 2, 5], 5)
assert a == 2
a = bsearch_left_not_less([1, 2, 5], 2)
assert a == 1
a = bsearch_left_not_less([1, 2, 3, 3, 5], 2)
assert a == 1
a = bsearch_left_not_less([1, 2, 3, 3, 5], 6)
assert a == -1
a = bsearch_left_not_less([], 1)
assert a == -1
a = bsearch_left_not_less([1], 1)
assert a == 0


if __name__ == "__main__":
a = [1, 1, 2, 3, 4, 6, 7, 7, 7, 7, 10, 22]

Expand All @@ -86,9 +106,7 @@ def bsearch_right_not_greater(nums: List[int], target: int) -> int:
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)
test_bsearch_left_not_less()

print(bsearch_right_not_greater(a, 0) == -1)
print(bsearch_right_not_greater(a, 6) == 5)
Expand Down