-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontains_by_binary_search.py
More file actions
48 lines (44 loc) · 1.53 KB
/
contains_by_binary_search.py
File metadata and controls
48 lines (44 loc) · 1.53 KB
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
36
37
38
39
40
41
42
43
44
45
46
47
48
'''
Contains
The second variation is a function that returns a boolean value indicating whether an element is present, but with no information about the location of that element.
For example:
letters = ['a', 'c', 'd', 'f', 'g']
print(contains('a', letters)) ## True
print(contains('b', letters)) ## False
There are a few different ways to approach this, so try it out, and we'll share two solutions after.
'''
def recursive_binary_search(target, source, left=0):
if len(source) == 0:
return None
center = (len(source) - 1) // 2
if source[center] == target:
return center
elif target < source[center]:
return recursive_binary_search(target, source[:center], left)
else:
return recursive_binary_search(target, source[center + 1:], left + center + 1)
# recursive
def contains_recursive(target, source):
return recursive_binary_search(target, source) is not None
# iterative
def contains(target, source):
min = 0
max = len(source) - 1
while min <= max:
mid = (min + max) // 2
if target == source[mid]:
return True
elif target < source[mid]:
max = mid - 1
else:
min = mid + 1
return False
letters = ['a', 'c', 'd', 'f', 'g']
print(contains('a', letters)) ## True
print(contains('b', letters)) ## False
answers = [contains('a', letters), contains('b', letters), contains_recursive('a', letters), contains_recursive('b', letters)]
for answer in answers:
if answer == True:
print('Pass!')
else:
print('Fail!')