-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathbinary_search.py
35 lines (31 loc) · 1.04 KB
/
binary_search.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
"""
提目:二分查找
"""
import unittest
def binary_search(arr: list, x: int):
if len(arr) == 1 and arr[0] != x:
return False
mid_index = len(arr) // 2
mid = arr[mid_index]
if x == mid:
return True
elif x < mid:
return binary_search(arr[:mid_index], x)
elif x > mid:
return binary_search(arr[mid_index + 1:], x)
else:
return False
class Test(unittest.TestCase):
def test(self):
arr = [1, 3, 4, 6, 7, 9, 13]
self.assertEqual(True, binary_search(arr, 7))
self.assertEqual(True, binary_search(arr, 1))
self.assertEqual(True, binary_search(arr, 13))
self.assertEqual(True, binary_search(arr, 6))
self.assertEqual(False, binary_search(arr, 2))
self.assertEqual(False, binary_search(arr, 0))
self.assertEqual(False, binary_search(arr, 15))
arr = [2, 2, 2, 2]
self.assertEqual(False, binary_search(arr, 3))
self.assertEqual(False, binary_search(arr, 1))
self.assertEqual(True, binary_search(arr, 2))