Skip to content

Instantly share code, notes, and snippets.

@BlackHC
Created March 11, 2024 16:50
Show Gist options
  • Save BlackHC/2bb5725f40f005c4b9b8fda7eb64051d to your computer and use it in GitHub Desktop.
Save BlackHC/2bb5725f40f005c4b9b8fda7eb64051d to your computer and use it in GitHub Desktop.
Scott Aaronson Oracle
# %%
import collections
import random
def predict_next_letter(model, five_gram):
if len(five_gram) != 5:
raise ValueError("five_gram must be of length 5")
m = model[tuple(five_gram)]
return m[True] > m[False]
def train_fivegrams(input_s):
model = collections.defaultdict(lambda: [0, 0])
# Generate all six-grams from the input sequence
six_grams = [input_s[i : i + 6] for i in range(len(input_s) - 5)]
for s in six_grams:
five_gram = s[:5]
last = s[-1]
model[tuple(five_gram)][last] += 1
return model
# %%
def round(num):
return int(num * 100)
def predict(model, press_q):
if len(press_q) < 5:
raise ValueError("press_q must be of length 5 or greater")
else:
five_gram = press_q[-5:]
return predict_next_letter(model, five_gram)
press_q = []
correct_predictions = 0
print("Press 'f' or 'd' (or 'q' for quit and 'm' for model): ")
while True:
model = train_fivegrams(press_q) # Retrain the model with the history
# Also draw a random number to simulate the user's behavior (50:50)
# press = "f" if random.random() > 0.5 else "d"
press = input()
if press in ["f", "d"]:
yes_no = True if press == "f" else False
if len(press_q) > 20:
predicted_yes_no = predict(model, press_q)
correct_predictions += predicted_yes_no == yes_no
accuracy = correct_predictions / (len(press_q) - 20)
prediction = "f" if predicted_yes_no else "d"
print(f"Predicted: {prediction}, Accuracy: {round(accuracy)}%")
else:
print("Learning...")
press_q.append(yes_no)
if press == "q":
break
if press == "m":
print(model)
# %%
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment