Created
April 26, 2022 13:10
-
-
Save autf/3ef4138587f27f4e541cb9e1819b5a3a to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import sys | |
from operator import gt, ge | |
cmp = ge | |
def search(a, x): | |
print('search:', x) | |
i, j = 0, len(a) | |
while i < j: | |
h = (i+j) // 2 | |
show(a,i,j) | |
# if a[h] >= x: # bisect_left | |
# if a[h] > x: # bisect_right | |
if cmp(a[h], x): | |
j = h | |
else: | |
i = h + 1 | |
show(a,i,j) | |
def get(i): | |
try: | |
return a[i] | |
except: | |
return float('inf') | |
assert i == j | |
print('got:', get(i)) | |
print() | |
def show(a, i, j): | |
h = (i+j) // 2 | |
print(*a[:i], '[', *a[i:h], '/', *a[h:j], ']', *a[j:]) | |
def repl(): | |
1/0 # TODO | |
# Python3.10+ needed | |
match sys.argv: | |
case [_, n, x]: | |
search(range(int(n)), float(x)) | |
case [_, n]: | |
a = range(n := int(n)) | |
for x in range(-1, n+1): | |
search(a, x) | |
case [_, *xs, x, f]: | |
if f[0] == 'r': | |
cmp = gt | |
search([*map(int, xs)], float(x)) | |
case _: | |
repl() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment