Created
April 1, 2017 13:09
-
-
Save nyeecola/40577fcbb61052b8ed3bc529842bf94c to your computer and use it in GitHub Desktop.
final caesar
This file contains 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
text = u'In cryptography, a Caesar cipher, also known as Caesar\'s cipher, the shift cipher, Caesar\'s code or Caesar shift, is one of the simplest and most widely known encryption techniques. It is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. For example, with a left shift of 3, D would be replaced by A, E would become B, and so on. The method is named after Julius Caesar, who used it in his private correspondence.' | |
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'] | |
attempts = [] | |
guessed = False | |
# there are 26 possible ceasar's cyphers "variations" | |
for i in range(0, 26): | |
# shift letters `i` times to the right | |
dec_text = '' | |
for c in text: | |
if ord(c) >= ord('a') and ord(c) <= ord('z'): | |
dec_text += chr((((ord(c) + i) - ord('a')) % 26) + ord('a')) | |
elif ord(c) >= ord('A') and ord(c) <= ord('Z'): | |
dec_text += chr((((ord(c) + i) - ord('A')) % 26) + ord('A')) | |
else: | |
dec_text += c | |
# count groups of 3 or more consonants to estimate the likelihood of the text being right | |
consecutive_consonants = 0 | |
consonant_factor = 0 | |
for c in dec_text: | |
if ((c in vowels) == True) or ((ord(c) < ord('a')) and (ord(c) > ord('Z'))) or (ord(c) > ord('z')) or (ord(c) < ord('A')): | |
consecutive_consonants = 0 | |
continue | |
consecutive_consonants += 1 | |
if consecutive_consonants >= 3: | |
consonant_factor += 1 | |
consecutive_consonants = 0 | |
# structure the data obtained | |
result = { | |
'dec_text': dec_text, | |
'consonant_factor': consonant_factor | |
} | |
# store attempts in order of most likely to be right to less likely to be right | |
index = 0 | |
for attempt in attempts: | |
if attempt['consonant_factor'] > result['consonant_factor']: | |
break | |
index += 1 | |
attempts.insert(index, result) | |
# print the most probable results | |
for attempt in attempts: | |
if attempt['consonant_factor'] == attempts[0]['consonant_factor']: | |
print attempt['dec_text'] | |
else: | |
break |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment