Skip to content

Instantly share code, notes, and snippets.

@peregrinogris
Created June 27, 2016 17:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peregrinogris/e395060687886831cf69ebca7df1f819 to your computer and use it in GitHub Desktop.
Save peregrinogris/e395060687886831cf69ebca7df1f819 to your computer and use it in GitHub Desktop.
Search for the maximum valid number in a range. Useful for scanning sequential ids and quickly (O(log(max_value))) find the maximum valid id.
class MaxSearch:
def __init__(self, max_value=2**16):
self.max_value = max_value
# Override this method with your validity check
def check_result(self, number):
pass
def scan(self, min_=0):
max_ = self.max_value
while True:
pivot = min_ + (max_ - min_) / 2
if self.check_result(pivot):
min_ = pivot
# We got to the end
if max_ - min_ == 1:
break
else:
max_ = pivot
return pivot
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment