Skip to content

Instantly share code, notes, and snippets.

@aglove2189
Created June 29, 2023 15:22
Show Gist options
  • Save aglove2189/a2f05d2bec71e08cdca69b0e93cf3009 to your computer and use it in GitHub Desktop.
Save aglove2189/a2f05d2bec71e08cdca69b0e93cf3009 to your computer and use it in GitHub Desktop.
Aaronson Oracle
from collections import defaultdict, deque
class Model:
def __init__(self):
self.counts = defaultdict(lambda: {"f": 0, "d": 0})
self.last_six = deque(maxlen=6)
self.num_correct = 0
self.num_predictions = 0
def fit(self, x):
if x in ("f", "d"):
self.last_six.append(x)
def predict(self, x):
if len(self.last_six) >= 5:
fivegram = "".join(list(self.last_six)[:5])
m = self.counts[fivegram]
prediction = "f" if not m or m["f"] > m["d"] else "d"
# update counts and accuracy
self.counts[fivegram][x[-1]] += 1
self.num_predictions += 1
self.num_correct += prediction == x
return prediction
def fit_predict(self, x):
self.fit(x)
return self.predict(x)
@property
def accuracy(self):
return round((self.num_correct / self.num_predictions) * 100)
def cli():
from getch import getch
model = Model()
print("Start typing, only 'f' or 'd' are allowed")
while True:
char = getch()
prediction = model.fit_predict(char)
msg = f"observed {char}"
if prediction is not None:
msg += f" predicted {prediction}"
if model.num_predictions > 9:
msg += f" {model.accuracy}% accurate"
print(msg)
if __name__ == "__main__":
cli()
@aglove2189
Copy link
Author

Start typing, only 'f' or 'd' are allowed
observed f
observed d
observed d
observed f
observed f predicted d
observed d predicted f
observed d predicted d
observed f predicted d
observed d predicted d
observed f predicted d
observed d predicted d
observed f predicted d
observed f predicted d
observed d predicted d 40% accurate
observed f predicted d 36% accurate
observed d predicted d 42% accurate
observed d predicted d 46% accurate
observed f predicted d 43% accurate
observed d predicted d 47% accurate
observed f predicted f 50% accurate
observed d predicted d 53% accurate
observed f predicted f 56% accurate
observed d predicted f 53% accurate
observed f predicted f 55% accurate
observed f predicted d 52% accurate
observed d predicted d 55% accurate
observed f predicted f 57% accurate
observed d predicted d 58% accurate
observed d predicted d 60% accurate
observed f predicted f 62% accurate
observed f predicted d 59% accurate
observed d predicted d 61% accurate
observed f predicted d 59% accurate
observed d predicted d 60% accurate
observed f predicted d 58% accurate
observed d predicted f 56% accurate
observed f predicted f 58% accurate
observed d predicted d 59% accurate

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