Advanced · Searching · 200 of 264
How many in range?
Answer many questions: how many numbers of the list lie between a and b (both included)? Sort once and use binary search (bisect) for each question.
Input: the numbers on one line, then q, then q lines "a b". Output: one count per question.
Examples
Input
5 1 9 3 7 3 2 6 0 10 4 4
Output
2 5 0
Input
1 1 1 1
Output
1
One more test checks other inputs when you press Check.
Stuck? The idea behind searching
Linear search looks at each item in turn. Binary search works on a sorted list: look at the middle, then throw away the half that can't hold the answer.
Binary search finds an item among a million in about 20 steps.
def find(a, target):
lo, hi = 0, len(a) - 1
while lo <= hi:
mid = (lo + hi) // 2
if a[mid] == target:
return mid
if a[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1Watch for: lo = mid instead of mid + 1 can loop for ever when two items are left.