Back to Freecodecamp

Step 16

curriculum/challenges/english/blocks/workshop-binary-search/68416d66013635cb6325eb6d.md

latest2.0 KB
Original Source

--description--

One final small enhancement you can add is to also show the index at which the target value is found.

So, instead of returning only path_to_target in the if statement, add an f-string with the message Value found at index {mid}.

With that, your binary search algorithm workshop is complete!

--hints--

You should return path_to_target, f'Value found at index {mid}' inside the if block.

js
({
    test: () => 
        assert(
            runPython(
                `_Node(_code).find_function("binary_search").find_whiles()[0].find_body().find_ifs()[0].find_body().is_equivalent("return path_to_target, f'Value found at index {mid}'")`
            )       
        )
})

--seed--

--seed-contents--

py
def binary_search(search_list, value):
    path_to_target = []
    low = 0
    high = len(search_list) - 1
    while low <= high:
        mid = (low + high) // 2
        value_at_middle = search_list[mid]
        path_to_target.append(value_at_middle)

        if value == value_at_middle:
            --fcc-editable-region--
            return path_to_target
            --fcc-editable-region--
        elif value > value_at_middle:
            low = mid + 1
        else:
            high = mid - 1

    return [], "Value not found"

print(binary_search([1, 2, 3, 4, 5], 3))
print(binary_search([1, 2, 3, 4, 5, 9], 4))
print(binary_search([1, 3, 5, 9, 14, 22], 10))

--solutions--

py
def binary_search(search_list, value):
    path_to_target = []
    low = 0
    high = len(search_list) - 1

    while low <= high:
        mid = (low + high) // 2
        value_at_middle = search_list[mid]
        path_to_target.append(value_at_middle)

        if value == value_at_middle:
          return path_to_target, f"Value found at index {mid}"
        elif value > value_at_middle:
            low = mid + 1
        else:
            high = mid - 1

    return [], "Value not found"

print(binary_search([1, 2, 3, 4, 5], 3))
print(binary_search([1, 2, 3, 4, 5, 9], 4)) 
print(binary_search([1, 3, 5, 9, 14, 22], 10))