Python: Binary search
Python Search and Sorting : Exercise-1 with Solution
Write a Python program for binary search.
Binary Search : In computer science, a binary search or half-interval search algorithm finds the position of a target value within a sorted array. The binary search algorithm can be classified as a dichotomies divide-and-conquer search algorithm and executes in logarithmic time.
Step by step example :

Sample Solution:
Python Code:
def binary_search(item_list,item):
first = 0
last = len(item_list)-1
found = False
while( first<=last and not found):
mid = (first + last)//2
if item_list[mid] == item :
found = True
else:
if item < item_list[mid]:
last = mid - 1
else:
first = mid + 1
return found
print(binary_search([1,2,3,5,8], 6))
print(binary_search([1,2,3,5,8], 5))
Sample Output:
False True
Flowchart:

Visualize Python code execution:
The following tool visualize what the computer is doing step-by-step as it executes the said program:
Python Code Editor :
Contribute your code and comments through Disqus.
Previous: Python Search and Sorting Exercise Homes.
Next: Write a Python program for sequential search.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Python: Tips of the Day
Enum Class:
Here is another classy approach from Python, no pun intended. Python's enum class will let you create enum object members with constant and unique values which then can be listed, compared or used for identification.
Enum classes are also iterable so they can be iterated as well:
from enum import Enum class sports(Enum): volleyball = 1 soccer = 2 running = 3 football = 4 baseball = 5 boxing = 6 print(sports.baseball) print(repr(sports.baseball))
Output:
sports.baseball <sports.baseball: 5>
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises