简体   繁体   中英

Python Caesar cypher using the most common letter to decode a message

I'm trying to create a Caesar cypher decoder that takes in a coded message, looks for the most common letter used, assumes this letter is "e" (since it is the most commonly used letter), and then shifts the letters the correct amount of places until the whole message is decoded.

The coder only works with strings large enough to get a good reading on all the letters used, and rides on the hope that the string is an average sentence where "e" is used the most, but I'm not sure how to do this...

I'm new to Python and the first thing I thought of was to make a list of counters for each letter then check the number of instances each letter has in the string, adding 1 to whichever counter the letter works with. I don't know how to put this into code though...

Counter can do most of the hard work for you:

>>> letters = 'imtryingtocreateacaesarcypherdecoder'
>>> c = collections.Counter(letters)

This gives you a mapping, where the letter 'e' is mapped to 6, 'r' to 5, 'c' and 'a' to 4, and so on. To find the most common letter, you just call the method most_common :

>>> c.most_common(1)
[('e', 6)]
>>> c.most_common(1)[0][0]
'e'

So, the only problem you have left is how to take your coded message, throw away all of the non-letters, and turn all of the letters into lowercase. If you look at the methods of the str type, you should be able to figure this out pretty easily.

(You might also want to use filter , or a comprehension; you may find that easier than something like str.translate . You don't actually need a string to pass to Counter , just any iterable of letters; a list or a generator expression is fine.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM