Binary Search Variant With Lower Bound (Python)
Find the leftmost position where a sorted list can accept a target using bisect-style binary search lower bound.
Code
def lower_bound(arr, target):
lo, hi = 0, len(arr)
while lo < hi:
mid = (lo + hi) // 2
if arr[mid] < target:
lo = mid + 1
else:
hi = mid
return lo
arr = [1, 2, 2, 3, 4, 6]
assert lower_bound(arr, 2) == 1
assert lower_bound(arr, 5) == 5What the code does
The working surface is the function lower_bound — everything else is wiring.
Repetition is confined to while lo < hi — the rest of the file is straight-line.
Applying it
The primary signature is def lower_bound(arr, target)
lower_bound is what another module would consume; nothing else here is load-bearing for callers.
Statements that matter
def lower_bound(arr, target):
lo, hi = 0, len(arr)
while lo < hi:
mid = (lo + hi) // 2
if arr[mid] < target:
lo = mid + 1
else:
hi = mid
return lo
Interactive Tools for This Topic
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Binary Text ConverterConvert UTF-8 text to 8-bit binary groups and decode binary back to text with strict validation.Bitwise Operations CalculatorCompute AND, OR, XOR, NOT, and shifts on 32-bit unsigned operands with binary, hex, and signed decimal views.Hex Dump ViewerPreview any text as a classic hexadecimal dump with byte offsets, sixteen bytes per row, and an ASCII column for quick inspection.
FAQ
- Anything to download besides the language toolchain?
- Nothing beyond the toolchain you already have for this language. The file defines `lower_bound` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.