Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 1ac4452

Browse files
authored
Create Exercise-20-Element-Search.py
1 parent cd4d3d4 commit 1ac4452

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

‎Exercise-20-Element-Search.py‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
'''
2+
Exercise 20: Element Search
3+
4+
Write a function that takes an ordered list of numbers (a list
5+
where the elements are in order from smallest to largest) and
6+
another number. The function decides whether or not the given
7+
number is inside the list and returns (then prints) an
8+
appropriate boolean.
9+
10+
Extras:
11+
Use binary search.
12+
13+
'''
14+
15+
# Solution
16+
def search_in_simple(number_list, query):
17+
"""
18+
Search query in number_list or not.
19+
20+
Arguments:
21+
number_list -- a list contain all the elements.
22+
query -- a element
23+
24+
Returns:
25+
True/False -- if query in number_list return True, else return False
26+
"""
27+
if query in number_list:
28+
return True
29+
else:
30+
return False
31+
32+
def search_in_binary(number_list, start, end, query):
33+
"""
34+
Search query in number_list or not.
35+
36+
Arguments:
37+
number_list -- a list contain all the elements.
38+
start -- start index.
39+
end -- end index.
40+
query -- a element.
41+
42+
Returns:
43+
True/False -- if query in number_list return True, else return False
44+
"""
45+
if start > end:
46+
return False
47+
mid = int(start + (end - start) / 2)
48+
if number_list[mid] > query:
49+
return search_in_binary(number_list, start, mid - 1, query)
50+
if number_list[mid] < query:
51+
return search_in_binary(number_list, mid + 1, end, query)
52+
return True
53+
54+
def main():
55+
number_list = [1, 2, 3, 4, 6, 7, 8, 9]
56+
query1 = 4
57+
query2 = 5
58+
print(search_in_simple(number_list, query1))
59+
print(search_in_binary(number_list, 0, len(number_list), query1))
60+
print(search_in_simple(number_list, query2))
61+
print(search_in_binary(number_list, 0, len(number_list), query2))
62+
63+
if __name__ == "__main__":
64+
main()

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /