Reputation: 44
first time posting to Stackoverflow!
I'm a new programmer so bear with me please, as I am not yet up to date with all the functions possible, so it may be that I am just currently missing the knowledge of a function or method that can solve my problem quickly.
I am attempting to make a python 3 script that can decrypt an encrypted text that uses the caesar cipher. I have currently made it so my code compares the encrypted text to a string of the alphabet, then stores the top 3 most common letters. Punctuation was not a problem here, for some reason.
When it came to decrypting the text, the program cannot make it past any punctuation. It decryps by shifting the alphabet so that the most common letter becomes "E". I cannot fathom a way to ask python to simply ignore and print the punctuation. I have made a string containing the punctuation separately, but I do not know what more to do from here. Code is attached below, in Python 3
All help appreciated!
#string used for comparing code to
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
#strings for shifting the code
shift = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ"
punctuation = ".,!;:?"
#ask user for the encrypted text
code = input("Enter text: ")
#variables storing the most common letters and the # of times they come up
common1 = 0
common2 = 0
common3 = 0
ac = 0
bc = 0
cc = 0
for i in range(0, len(alphabet)):
# print number of times each letter comes up --- print( str(alphabet[i]) + " is present " + str(code.count(alphabet[i])) + " number of times" )
#finding the number of times the most common letter comes up
if code.count(alphabet[i]) > common1:
common3 = common2
cc = bc
common2 = common1
bc = ac
common1 = code.count(alphabet[i])
ac = alphabet[i]
elif code.count(alphabet[i]) > common2:
common3 = common2
cc = bc
common2 = code.count(alphabet[i])
bc = alphabet[i]
elif code.count(alphabet[i]) > common3:
common3 = code.count(alphabet[i])
cc = alphabet[i]
print("Most common letter, " + str(ac) + ", comes up " + str(common1) + " times")
print("Second most common letter, " + str(bc) + ", comes up " + str(common2) + " times")
print("Third most common letter, " + str(cc) + ", comes up " + str(common3) + " times")
for i in range(0, len(code)):
a = shift.index("E") + 26 - shift.index(ac)
print(shift[a + shift.index( code[i] ) ], end = "")
Upvotes: 0
Views: 499
Reputation: 1218
You should check that the value of the code at each position is in your alphabet. If not just print the value from the code and continue to the next loop.
for i in range(0, len(code)):
if code[i] not in alphabet:
print(code[i])
continue
a = shift.index("E") + 26 - shift.index(ac)
print(shift[a + shift.index( code[i] ) ], end = "")
Upvotes: 1