Skip to content

Instantly share code, notes, and snippets.

@minte9
Last active June 6, 2021 09:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save minte9/4c411d0c83cfdfa718085f792f810a18 to your computer and use it in GitHub Desktop.
Save minte9/4c411d0c83cfdfa718085f792f810a18 to your computer and use it in GitHub Desktop.
Python / Language / Binary search
# 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