Skip to content

Commit 2c238b9

Browse files
authored
Add files via upload
1 parent d5acbbe commit 2c238b9

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

Diff for: ElementSearch.py

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# Write a function that takes an ordered list of numbers (a list where
2+
# the elements are in order from smallest to largest) and another number.
3+
# The function decides whether or not the given number is inside the list
4+
# and returns (then prints) an appropriate boolean.
5+
# Extras:
6+
# Use binary search.
7+
8+
def search(myset, num):
9+
'''
10+
Takes in an ordered list or set, and a number to search for
11+
Uses binary search to see if the number is in the list
12+
Return True if it is or False if it isn't
13+
'''
14+
foundnum = None
15+
while len(myset) >= 1: #if the halved list is over 1 and we haven't found the number we're searching for, keep searching
16+
foundnum = myset[int((len(myset)-1)/2)]
17+
if foundnum == num:
18+
return True
19+
elif(foundnum < num):
20+
myset = myset[int((len(myset)-1)/2)+1:len(myset)]
21+
else: #foundnum > num
22+
myset = myset[0:int((len(myset)-1)/2)]
23+
return False
24+
25+
26+
if __name__ == "__main__":
27+
myseta = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
28+
mysetb = [1, 3, 5, 30, 42, 43, 500, 700]
29+
num = 13
30+
print(search(mysetb, num))

0 commit comments

Comments
 (0)