Last active
June 6, 2021 09:40
-
-
Save minte9/4c411d0c83cfdfa718085f792f810a18 to your computer and use it in GitHub Desktop.
Python / Language / Binary search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Make a Bisection Search (or binary search), | |
# similar to what you do in dictionary. | |
# You start in the middle of the list, then you search the second half | |
# https://github.com/AllenDowney/ThinkPython2/blob/master/code/words.txt | |
# Word List | |
words = [] | |
for line in open("/var/www/python/words.txt"): | |
word = line.strip() | |
words.append(word) | |
# Full Search | |
def search(keyword, words): | |
i = 0 | |
for word in words: | |
i += 1 | |
if word == keyword: | |
print(i) | |
return True | |
print(i) | |
return False | |
# SOLUTION | |
# Bisect Search | |
def search_bisect(keyword, words, loops=0): | |
loops += 1 | |
i = len(words) // 2 # Look Here | |
if words[i] == word: | |
print(loops) | |
return True | |
if word < words[i]: | |
search_bisect(keyword, words[:i], loops) | |
else: | |
search_bisect(keyword, words[i+1:], loops) | |
return False | |
search("mother", words) # 62889 | |
search_bisect("mother", words) # 16 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment