forked from slytherins-hub/lecture_searching
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearching.py
More file actions
72 lines (63 loc) · 2.03 KB
/
searching.py
File metadata and controls
72 lines (63 loc) · 2.03 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import json
import os
import time
from itertools import count
# get current working directory path
cwd_path = os.getcwd()
def read_data(file_name, field):
"""
Reads json file and returns sequential data.
:param file_name: (str), name of json file
:param field: (str), field of a dict to return
:return: (list, string),
"""
if field not in {"unordered_numbers", "ordered_numbers", "dna_sequence"}:
return None
file_path = os.path.join(cwd_path, file_name)
with open(file_path,mode="r") as json_file:
sequential_data = json.load(json_file)
return sequential_data[field]
def linear_search(sequence:list, number):
list_of_index = []
count_index = 0
index = 0
while index < len(sequence):
if sequence[index]==number:
count_index += 1
list_of_index.append(index)
index += 1
return {
"position": list_of_index,
"count": count_index
}
def pattern_search(sequence:list, pattern):
index_set = set()
index = 0
while index <= len(sequence) - len(pattern):
if sequence[index : index+len(pattern)] == pattern:
index_set.add(index)
index+=1
return index_set
def binary_search(ordered_list:list, number:int)->int|None:
left_index = 0
right_index = len(ordered_list)
middle_index = int(right_index / 2)
while left_index <= right_index:
if ordered_list[middle_index]==number:
return middle_index
elif ordered_list[middle_index] > number:
right_index = middle_index-1
else:
left_index = middle_index+1
middle_index = (right_index+left_index)//2
def main():
file_name = "sequential.json"
seq = read_data(file_name, field="ordered_numbers")
print(seq)
start = time.time()
set_seq = binary_search(seq,120)
finish = time.time()
time_code = finish-start
print(f"{set_seq}, {time_code}")
if __name__ == '__main__':
main()