cryptography - Decrypting substitution cipher in Python yields correct substitutions for some letters, but not others -
to me learn python, have been working on small script decrypt simple substitution cipher on python challenge. if wish avoid potential spoilers, please stop here.
the ciphertext rotated 2 steps , ciphertext input follows:
thread = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj." the script used follows, comments.
cipher = "abcdefghijklmnopqrstuvwxyz" letter in thread: if letter in cipher , cipher.index(letter) <= 23: # if character in alphabet , between a-x... thread = thread.replace(letter, cipher[cipher.index(letter) + 2], 1) # replace letter 1 2 letters after it, , save elif letter in cipher , cipher.index(letter) > 23: # if character y or z... thread = thread.replace(letter, cipher[cipher.index(letter) - 24], 1) # replace , b, respectively print(thread) this yields output of:
o hoti ioi hihtt tterapati ha hand. thaty uhat aoonutets ate dot. doine in dw hand ineddiaient , thyt's ufw rfis rexr gs none. ssgne srrgne.oyierpyns() gs peammkcnbcb. lmu ynnlw ml rfc spl. the thing stuck out me first letter (g) incorrectly transposed 8 steps. however, second letter (f) correctly transposed 2 steps. other incorrect letters appear transposed different amounts. went , took apart code check if individual parts worked:
print(cipher[cipher.index("g") + 2]) # bit functional , converts letters a-x shift of 2. more specifically, correctly convert g i. print(cipher[cipher.index("y") - 24]) # functional , converts y , z i not sure wrong script. appreciated.
ok , how solved , based on code :
thread = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj." cipher = "abcdefghijklmnopqrstuvwxyz" thread_decrypted = '' ## used empty string append rotated letters ## letter in thread: if letter in cipher : if cipher.index(letter) <= 23 : thread_decrypted += cipher[ cipher.index(letter) + 2 ] else : thread_decrypted += cipher[ cipher.index(letter) -24 ] else : thread_decrypted += letter print(thread_decrypted) a simpler, more 'pythonic' way :
thread = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj." cipher = "abcdefghijklmnopqrstuvwxyz" thread_decrypted = ''.join( cipher[ ( cipher.index(l) + 2 ) % 26 ] if l in cipher else l l in thread ) print(thread_decrypted) which loop in 1 line ( list comprehension ) .
the problem code use replace() .
every time iterate original string gets mutated
( 'a' becomes 'c' , becomes 'e', etc ) ,
, thats why errors .
i hope helps, luck studies
Comments
Post a Comment