Hacking Secret Ciphers with Python

(Ann) #1

264 http://inventwithpython.com/hacking


Email questions to the author: [email protected]



  1. else:


  2. If a letter in mapA[letter] exists in mapB[letter], add




  3. that letter to intersectedMapping[letter].



  4. for mappedLetter in mapA[letter]:

  5. if mappedLetter in mapB[letter]:

  6. intersectedMapping[letter].append(mappedLetter)



  7. return intersectedMapping





  8. def removeSolvedLettersFromMapping(letterMapping):


  9. Cipher letters in the mapping that map to only one letter are




  10. "solved" and can be removed from the other letters.




  11. For example, if 'A' maps to potential letters ['M', 'N'], and 'B'




  12. maps to ['N'], then we know that 'B' must map to 'N', so we can




  13. remove 'N' from the list of what 'A' could map to. So 'A' then maps




  14. to ['M']. Note that now that 'A' maps to only one letter, we can




  15. remove 'M' from the list of letters for every other




  16. letter. (This is why there is a loop that keeps reducing the map.)



  17. letterMapping = copy.deepcopy(letterMapping)

  18. loopAgain = True

  19. while loopAgain:


  20. First assume that we will not loop again:



  21. loopAgain = False




  22. solvedLetters will be a list of uppercase letters that have one




  23. and only one possible mapping in letterMapping



  24. solvedLetters = []

  25. for cipherletter in LETTERS:

  26. if len(letterMapping[cipherletter]) == 1:

  27. solvedLetters.append(letterMapping[cipherletter][0])




  28. If a letter is solved, than it cannot possibly be a potential




  29. decryption letter for a different ciphertext letter, so we




  30. should remove it from those other lists.



  31. for cipherletter in LETTERS:

  32. for s in solvedLetters:

  33. if len(letterMapping[cipherletter]) != 1 and s in
    letterMapping[cipherletter]:

  34. letterMapping[cipherletter].remove(s)

  35. if len(letterMapping[cipherletter]) == 1:


  36. A new letter is now solved, so loop again.



  37. loopAgain = True

  38. return letterMapping





Free download pdf