Skip to content
Exercise · Final project · lesson 6 of 8

Exercise: binary search

Write a function binary_search(nums, target) that looks for the number target in the sorted list nums with binary search. It returns the index of the element found, or -1 if the list has no such number. Do not use the bisect module.

  • binary_search([3, 8, 15, 21, 30], 15) → 2
  • binary_search([3, 8, 15, 21, 30], 10) → -1
  • binary_search([], 7) → -1

Constraints: nums holds from 0 to 1000 integers sorted in ascending order, all of them different; target may be less than every element or greater than every one; for an empty list the function returns -1.

Do not add extra imports unless the task says so explicitly.

binary_search.py — python
python · 3 lines
Ctrl+Enter run · Esc leave editor

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way