livepython.net

225. Python Program to Find a Number with Binary Search

HardPhase 3 · Challenge

This one takes a few steps. You know all the tools: split(), a while loop and the // sign. Follow a short list on paper first.

Overview

Binary search is one of the most famous ideas in programming, and a classic interview question. It finds a number in a sorted list very fast, because each check throws away half of the list.

Problem Statement

Amir has a sorted list of ticket numbers and wants to find one ticket fast, without looking at every number.

Binary search works like looking up a word in a paper dictionary. You open it in the middle, see if your word comes before or after that page, and forget the other half. Then you do the same with the half that is left.

Follow these rules exactly. low, high and the middle are indexes: list positions that start at 0, as in Python.

  • Start with low = 0 and high = the index of the last number.
  • While low is not bigger than high:
    • The middle index is (low + high) // 2. Look at the number there. This is one check.
    • If it is the target, stop: you found it.
    • If it is smaller than the target, the target can only be on the right. Set low to the middle index + 1.
    • If it is bigger than the target, the target can only be on the left. Set high to the middle index - 1.
  • If low gets bigger than high, nothing is left, and the target is not in the list.

Print two lines. If you found the target, print Position: <position>. The position counts from 1 here, so the first number is at position 1. If you did not find it, print Not found. On the second line, print Checks: <checks>, the number of checks the search made.

Examples

Example 1. Input:

3 8 12 17 23 31 40
23

gives:

Position: 5
Checks: 3

Why: check 1 looks at index 3, which is 17: too small, so low becomes 4. Check 2 looks at index 5, which is 31: too big, so high becomes 4. Check 3 looks at index 4, which is 23: found. Index 4 is position 5.

Example 2. Input:

2 4 6 8 10
5

gives:

Not found
Checks: 3

Why: the checks look at 6, then 2, then 4. After the third check, low is 2 and high is 1, so nothing is left to check.

Input

Two lines:

  • Line 1: whole numbers sorted from small to big, all different, with one space between them (1 number or more).
  • Line 2: the target, a whole number.

Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.

Output

Two lines: Position:, a space and the position, or Not found. Then Checks:, a space and the number of checks. The tests try 10 different inputs, also a list with one number and targets at both ends.

Try it first. The solution opens when you solve this question, or after 3 tries with Submit.

Finish this chapter firstChapter 12 · Working With Strings
solution.py
# write your code here

EXPECTED OUTPUT

1Position: 5
2Checks: 3

YOUR OUTPUT

Press Run to see your output here. Lines are compared with the expected output.