Skip to content

Instantly share code, notes, and snippets.

@omaraflak
Last active February 13, 2024 16:16
Show Gist options
  • Save omaraflak/fcf4abcbfaa295ef68bebcfe6cb579ba to your computer and use it in GitHub Desktop.
Save omaraflak/fcf4abcbfaa295ef68bebcfe6cb579ba to your computer and use it in GitHub Desktop.
Based on Aaronson Oracle
import sys
import getch
from collections import defaultdict
class Oracle:
def __init__(self, window_size: int):
self.window_size = window_size
self.window: str = ''
self.patterns: defaultdict[str, dict[str, int]] = defaultdict(lambda: defaultdict(int))
def observe(self, c: str):
if len(c) != 1:
return
self.window += c
if len(self.window) <= self.window_size:
return
key = self.window[:-1]
self.patterns[key][c] += 1
self.window = self.window[1:]
def predict(self, default: str) -> str:
if self.window not in self.patterns:
return default
return max(self.patterns[self.window].items(), key=lambda x: x[1])[0]
def main():
print('Press any of "j" or "f" repeatedly, I will try to predict your keystrokes.')
print('Press Escape to exit.')
total = 0
good = 0
oracle = Oracle(4)
while True:
c = oracle.predict('f')
print('> ', end='')
sys.stdout.flush()
s = getch.getch()
if ord(s) == 27:
break
s = 'f' if s == 'f' else 'j'
print(s, end='\t')
oracle.observe(s)
total += 1
if s == c:
good += 1
print(f'{100 * good / total:.0f}%')
sys.stdout.flush()
main()
@omaraflak
Copy link
Author

pip install getch

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment