view python/example/binarysearch.py @ 694:ebca6d85213a

File "/usr/lib/python3/dist-packages/IPython/config/__init__.py", line 16, in <module> from .application import * File "/usr/lib/python3/dist-packages/IPython/config/application.py", line 31, in <module> from IPython.config.configurable import SingletonConfigurable File "/usr/lib/python3/dist-packages/IPython/config/configurable.py", line 33, in <module> from IPython.utils.text import indent, wrap_paragraphs File "/usr/lib/python3/dist-packages/IPython/utils/text.py", line 28, in <module> from IPython.external.path import path File "/usr/lib/python3/dist-packages/IPython/external/path/__init__.py", line 2, in <module> from path import * File "/home/jhammel/python/path.py", line 25 print root(path) ^
author Jeff Hammel <k0scist@gmail.com>
date Wed, 09 Jul 2014 16:26:49 -0700
parents e3341b7ce4ef
children
line wrap: on
line source

#!/usr/bin/env python

def find_index(ordered_array, to_find):
    """
    Return index of ``to_find`` via binary search.
    Returns None if not in ``ordered_array``

    ordered_array -- array of ordered values
    to
    """
    if not ordered_array:
        return
    minimum = 0
    maximum = len(ordered_array)-1
    while True:
        middle = (minimum + maximum)/2
        value = ordered_array[middle]
        if value == to_find:
            return middle
        if maximum == minimum:
            return
        if value < to_find:
            minimum = middle+1
            continue
        if value > to_find:
            maximum = middle
            continue

if __name__ == '__main__':
    import unittest

    class TestFindIndex(unittest.TestCase):
        values = [1,2,4,8,16,17]
        def test_spotcheck(self):
            for index, value in enumerate(self.values):
                self.assertEqual(find_index(self.values, value), index)

    unittest.main()