-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathExercise-20-Element-Search.py
64 lines (53 loc) Β· 1.68 KB
/
Exercise-20-Element-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
56
57
58
59
60
61
62
63
64
'''
Exercise 20: Element Search
Write a function that takes an ordered list of numbers (a list
where the elements are in order from smallest to largest) and
another number. The function decides whether or not the given
number is inside the list and returns (then prints) an
appropriate boolean.
Extras:
Use binary search.
'''
# Solution
def search_in_simple(number_list, query):
"""
Search query in number_list or not.
Arguments:
number_list -- a list contain all the elements.
query -- a element
Returns:
True/False -- if query in number_list return True, else return False
"""
if query in number_list:
return True
else:
return False
def search_in_binary(number_list, start, end, query):
"""
Search query in number_list or not.
Arguments:
number_list -- a list contain all the elements.
start -- start index.
end -- end index.
query -- a element.
Returns:
True/False -- if query in number_list return True, else return False
"""
if start > end:
return False
mid = int(start + (end - start) / 2)
if number_list[mid] > query:
return search_in_binary(number_list, start, mid - 1, query)
if number_list[mid] < query:
return search_in_binary(number_list, mid + 1, end, query)
return True
def main():
number_list = [1, 2, 3, 4, 6, 7, 8, 9]
query1 = 4
query2 = 5
print(search_in_simple(number_list, query1))
print(search_in_binary(number_list, 0, len(number_list), query1))
print(search_in_simple(number_list, query2))
print(search_in_binary(number_list, 0, len(number_list), query2))
if __name__ == "__main__":
main()