forked from pa3cka/lecture_13
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary_search.py
55 lines (41 loc) · 1.38 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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import os
import json
cwd_path = os.getcwd()
file_path = 'files'
def read_data(file_name, key='ordered_numbers'):
"""
Reads json file and returns sequential data.
:param file_name: (str), name of json file
:param key: (str), field of a dict to return
:return: (list, string),
"""
if key not in {"unordered_numbers", "ordered_numbers", "dna_sequence"}:
return None
with open(os.path.join(cwd_path, file_path, file_name), 'r') as json_file:
seqs = json.load(json_file)
return seqs[key]
def binary_search(seq, number):
"""
Function performs binary search on !!ordered!! sequence and stores position of match if found.
:param seq: (list): list on numbers
:param number: (int): number to match within sequence
:return: (int, None): index of match if found, None otherwise
"""
left, right = (0, len(seq) - 1)
while left <= right:
middle = (right + left) // 2
if number < seq[middle]:
right = middle - 1
elif number > seq[middle]:
left = middle + 1
else:
return middle
return
def main(file_name, number):
sequence = read_data(file_name=file_name, key='ordered_numbers')
# iterative binary search
binary_search(sequence, number=number)
if __name__ == '__main__':
my_file = 'sequential.json'
my_number = 90
main(my_file, my_number)