Python Caesar Cipher Decoder

后端 未结 3 599
抹茶落季
抹茶落季 2021-01-03 06:00

In my lesson I was tasked with creating a Caesar Cipher decoder that takes a string of input and finds the best possible string using a letter frequencies. If not sure how m

3条回答
  •  独厮守ぢ
    2021-01-03 06:31

    Here is my implementation which works fine.

    You should print the goodness of each possible message and see why your program output it.

    letterGoodness = dict(zip(string.ascii_uppercase,
                            [.0817,.0149,.0278,.0425,.1270,.0223,.0202,
                             .0609,.0697,.0015,.0077,.0402,.0241,.0675,
                             .0751,.0193,.0009,.0599,.0633,.0906,.0276,
                             .0098,.0236,.0015,.0197,.0007]))
    
    trans_tables = [ str.maketrans(string.ascii_uppercase,
                     string.ascii_uppercase[i:]+string.ascii_uppercase[:i])
                     for i in range(26)]
    
    def goodness(msg):
        return sum(letterGoodness.get(char, 0) for char in msg)
    
    def all_shifts(msg):
        msg = msg.upper()
        for trans_table in trans_tables:
            txt = msg.translate(trans_table)
            yield goodness(txt), txt
    
    print(max(all_shifts(input())))
    

提交回复
热议问题