Python bootcamp · Lab 41

Binary search

mediumBinary Search15 minLesson: Binary Search

Read the question, write Python on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

The first line is n. The second line is n integers already sorted ascending. The third line is a target.

Print the 0-based index of the target, or -1 if it is missing. Use binary search (or bisect) — do not scan from the left.

Input. Line 1: n. Line 2: n sorted integers. Line 3: target.

Output. One integer: the index, or -1.

Constraints

  • 1 ≤ n ≤ 1000
  • The list is sorted ascending.

Examples

Example 1
Input
7
1 3 5 7 9 11 13
7
Output
3
Example 2
Input
5
1 2 3 4 5
6
Output
-1
Hint
  1. bisect.bisect_left finds the insertion point. If nums[i] == target, i is the index.
  2. By hand: lo, hi = 0, n-1; mid = (lo+hi)//2; shrink the half that cannot contain the target.
Show correct code

Peek only after you have tried. You can still Check your own version.

from bisect import bisect_left
n = int(input())
nums = list(map(int, input().split()))
target = int(input())
i = bisect_left(nums, target)
print(i if i < n and nums[i] == target else -1)
main.pyPython · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.