Created
June 4, 2016 21:54
-
-
Save Tsunamicom/893a974b017469002466d5438f031ca9 to your computer and use it in GitHub Desktop.
Binary Search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Written in Python 3.51 by Kurtis Mackey (Developed Test First) | |
# Binary Search | |
import unittest | |
def binary_search(array, num): | |
"""Given a sorted array of numbers, | |
return True of num is in the array | |
using Binary Search. | |
""" | |
if type(array) != type(list()): | |
raise TypeError('Must be of type: List()') | |
if array != sorted(array): | |
raise ValueError('Must be a Sorted Array for Binary Search') | |
mid = len(array)//2 | |
if array[mid] == num: | |
return True | |
else: | |
if num > array[-1] or num < array[0]: | |
return False | |
elif num <= array[mid]: | |
return binary_search(array[:mid], num) | |
elif num > array[mid]: | |
return binary_search(array[mid:], num) | |
else: | |
return False | |
# ================ TESTING =================== | |
class BinarySearchTest(unittest.TestCase): | |
def test_binary_searchTrue(self): | |
self.assertEqual(binary_search([1, 2, 3, 4, 5], 4), True) | |
self.assertEqual(binary_search([4, 5, 6, 7, 8, 9], 4), True) | |
self.assertEqual(binary_search([10, 20, 30, 40, 50], 50), True) | |
self.assertEqual(binary_search([10, 100, 150, 300, 301], 150), True) | |
self.assertEqual(binary_search([-1, 10, 100, 150, 300, 301], -1), True) | |
def test_binary_searchFalse(self): | |
self.assertEqual(binary_search([1, 2, 3, 4, 5], 10), False) | |
self.assertEqual(binary_search([4, 5, 6, 7, 8, 9], 0), False) | |
self.assertEqual(binary_search([10, 20, 30, 40, 50], 11), False) | |
self.assertEqual(binary_search([10, 100, 150, 300, 301], 151), False) | |
self.assertEqual(binary_search([10, 100, 150, 300, 301], -1), False) | |
def test_binary_searchError(self): | |
self.assertRaises(TypeError, binary_search, 1, 2) | |
self.assertRaises(TypeError, binary_search, 'abcde', 'b') | |
self.assertRaises(TypeError, binary_search, 'edcba', 'b') | |
self.assertRaises(ValueError, binary_search, [3, 2, 1], 2) | |
self.assertRaises(ValueError, binary_search, [4, 2, 1, 6, 1, 2], 15) | |
if __name__ == '__main__': | |
unittest.main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment