Skip to content

Commit 708818d

Browse files
committed
test: add doctests and edge case coverage for binary search on answer implementation
1 parent 1b68ef6 commit 708818d

1 file changed

Lines changed: 55 additions & 1 deletion

File tree

searches/binary_search_on_answers.py

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,34 @@ def binary_search_on_answer(
4040

4141
return answer
4242

43+
# Doctests-1. Doctests for binary_search_on_answer
44+
45+
"""
46+
Generic Binary Search on Answer template.
47+
48+
Finds the minimum value in the range [low, high] that satisfies the condition.
49+
50+
The condition must be monotonic:
51+
False False False True True True
52+
53+
Examples:
54+
>>> def condition(x): return x * x >= 16
55+
>>> binary_search_on_answer(0, 10, condition)
56+
4
57+
58+
>>> def condition(x): return x >= 7
59+
>>> binary_search_on_answer(0, 10, condition)
60+
7
61+
62+
>>> def condition(x): return x >= 0
63+
>>> binary_search_on_answer(-5, 5, condition)
64+
0
65+
66+
>>> def condition(x): return True
67+
>>> binary_search_on_answer(1, 5, condition)
68+
1
69+
"""
70+
4371

4472
# Example1: minimum capacity to ship
4573

@@ -63,4 +91,30 @@ def can_ship(capacity: int) -> bool:
6391

6492
return days_used <= days
6593

66-
return binary_search_on_answer(max(weights), sum(weights), can_ship)
94+
return binary_search_on_answer(max(weights), sum(weights), can_ship)
95+
96+
# Doctest-2. Doctests for min_capacity_to_ship
97+
98+
"""
99+
Find minimum capacity to ship packages within given days.
100+
101+
Examples:
102+
>>> min_capacity_to_ship([1,2,3,4,5,6,7,8,9,10], 5)
103+
15
104+
105+
>>> min_capacity_to_ship([3,2,2,4,1,4], 3)
106+
6
107+
108+
>>> min_capacity_to_ship([1,2,3,1,1], 4)
109+
3
110+
111+
>>> min_capacity_to_ship([10], 1)
112+
10
113+
"""
114+
115+
# Edge case to be handled
116+
"""
117+
>>> def condition(x): return x >= 100
118+
>>> binary_search_on_answer(0, 50, condition)
119+
50
120+
"""

0 commit comments

Comments
 (0)