Skip to content

Instantly share code, notes, and snippets.

@tgoldenberg
Created February 22, 2024 19:20
Show Gist options
  • Save tgoldenberg/d005a97496a0e7353089086c2b0ef683 to your computer and use it in GitHub Desktop.
Save tgoldenberg/d005a97496a0e7353089086c2b0ef683 to your computer and use it in GitHub Desktop.
import math
def search(l, term, offset=0):
# find the middle
# find length of list and divide by two
list_len = len(l)
if list_len <= 0:
return None
middle = math.floor(list_len / 2)
# print(l, term, middle)
if l[middle] == term:
# print("Found it! ", term, middle)
return middle + offset
elif l[middle] > term:
# discard right
return search(l[:middle], term)
elif l[middle] < term:
# discard left
return search(l[middle+1:], term, middle+1)
# print("Didn't find anything ...")
return None
print(search([1,2,3], 2))
print(search([1, 2, 3, 4, 5], 7))
print(search([1, 2, 3, 4, 5, 6, 7, 8], 7))
print(search([1, 3, 5, 7, 9, 11, 13, 15, 17, 19], 5))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment