Skip to content

Instantly share code, notes, and snippets.

@mhoffman
Created November 7, 2017 17:53
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 mhoffman/4e7f116bc4869107077cbac34c9a94a1 to your computer and use it in GitHub Desktop.
Save mhoffman/4e7f116bc4869107077cbac34c9a94a1 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import sys
import optparse
parser = optparse.OptionParser(
usage="""
usage: %prog [low] hi
Do an (integer) binary on the command line. Initial arguments are a lower and upper bound.
If only one argument is given, the lower bound will be assume 0. Iteratively state
h/l if the number you are looking for is higher/lower. Use k/j if are you used to vim keys.
"""
)
options, args = parser.parse_args()
if len(sys.argv) >= 2:
lower = int(float(sys.argv[0]))
upper = int(float(sys.argv[1]))
elif len(sys.argv) == 2:
upper = int(float(sys.argv[0]))
lower = 0
print("Assuming {lower} as lower bound".format(**locals()))
else:
parser.print_help()
raise UserWarning("Usage: bs <lower> <upper>")
while lower + 1 < upper:
median = ((lower + upper) / 2)
print("Median {median}, Lower {lower}, Upper {upper}".format(**locals()))
user_input = ''
print(user_input)
while user_input not in ['h', 'l', '=', 'j', 'k']:
user_input = raw_input("Higher [h/k], lower [l/j], or equal [=]? ")
if user_input in ['h', 'k']:
lower = median
elif user_input in ['l', 'j']:
upper = median
elif user_input == '=':
break
if user_input == 'h':
median = upper
elif user_input == 'l':
median = lower
print("\n\nFinal answer: {median}".format(**locals()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment