Skip to content

Instantly share code, notes, and snippets.

@MLWhiz
Created June 20, 2019 18:35
Show Gist options
  • Save MLWhiz/c5cfd01998dab46e4b0c4cf1a0e76e2e to your computer and use it in GitHub Desktop.
Save MLWhiz/c5cfd01998dab46e4b0c4cf1a0e76e2e to your computer and use it in GitHub Desktop.
# Takes as input a text to decrypt and runs a MCMC algorithm for n_iter. Returns the state having maximum score and also
# the last few states
def MCMC_decrypt(n_iter,cipher_text,scoring_params):
current_cipher = string.ascii_uppercase # Generate a random cipher to start
state_keeper = set()
best_state = ''
score = 0
for i in range(n_iter):
state_keeper.add(current_cipher)
proposed_cipher = generate_cipher(current_cipher)
score_current_cipher = get_cipher_score(cipher_text,current_cipher,scoring_params)
score_proposed_cipher = get_cipher_score(cipher_text,proposed_cipher,scoring_params)
acceptance_probability = min(1,math.exp(score_proposed_cipher-score_current_cipher))
if score_current_cipher>score:
best_state = current_cipher
if random_coin(acceptance_probability):
current_cipher = proposed_cipher
if i%500==0:
print("iter",i,":",apply_cipher_on_text(cipher_text,current_cipher)[0:99])
return state_keeper,best_state
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment