""" chop() binary search from http://codekata.pragprog.com/2007/01/kata_two_karate.html Programming Workshop | April 3 """ def chop(n, list): """ Return index of where n is in list, -1 if not found. """ if len(list) == 0: return -1 if len(list) == 1: if list[0] == n: return 0 else: return -1 split_index = len(list)/2 answer1 = chop(n, list[:split_index]) if answer1 != -1: return answer1 answer2 = chop(n, list[split_index:]) if answer2 != -1: return answer2 + split_index return -1 def assert_equal(a, b): assert a == b, "failed test" def test_chop(): assert_equal(-1, chop(3, [])) assert_equal(-1, chop(3, [1])) assert_equal(0, chop(1, [1])) # assert_equal(0, chop(1, [1, 3, 5])) assert_equal(1, chop(3, [1, 3, 5])) assert_equal(2, chop(5, [1, 3, 5])) assert_equal(-1, chop(0, [1, 3, 5])) assert_equal(-1, chop(2, [1, 3, 5])) assert_equal(-1, chop(4, [1, 3, 5])) assert_equal(-1, chop(6, [1, 3, 5])) # assert_equal(0, chop(1, [1, 3, 5, 7])) assert_equal(1, chop(3, [1, 3, 5, 7])) assert_equal(2, chop(5, [1, 3, 5, 7])) assert_equal(3, chop(7, [1, 3, 5, 7])) assert_equal(-1, chop(0, [1, 3, 5, 7])) assert_equal(-1, chop(2, [1, 3, 5, 7])) assert_equal(-1, chop(4, [1, 3, 5, 7])) assert_equal(-1, chop(6, [1, 3, 5, 7])) assert_equal(-1, chop(8, [1, 3, 5, 7])) print "Passed all tests." test_chop()