Caesar's Cipher using python, could use a little help

后端 未结 8 1362
时光说笑
时光说笑 2020-11-30 14:24

I\'m trying to make a \"Caesar\'s Cipher\" while using python..this is what I have so far. Could anyone tell me how this is looking? Am I going in the right direction? What

相关标签:
8条回答
  • 2020-11-30 15:23

    I very simple, 3-shift solution without Umlauts and alike would be:

    def caesar(inputstring):
        shifted=string.lowercase[3:]+string.lowercase[:3]
        return "".join(shifted[string.lowercase.index(letter)] for letter in inputstring)
    

    and reverse:

    def brutus(inputstring):
        shifted=string.lowercase[-3:]+string.lowercase[:-3]
        return "".join(shifted[string.lowercase.index(letter)] for letter in inputstring)
    

    using it:

    caesar("xerxes")
    
    0 讨论(0)
  • 2020-11-30 15:28

    Here is a different method to show how we can handle this in a very clean way. We define an input alphabet and an output alphabet, then a translation table and use unicode.translate() to do the actual encryption.

    import string
    # Blatantly steal Lennart's UI design
    first = unicode(raw_input("Please enter Plaintext to Cipher: "), "UTF-8")
    k = int(raw_input("Please enter the shift: "))
    
    in_alphabet = unicode(string.ascii_lowercase)
    out_alphabet = in_alphabet[k:] + in_alphabet[:k]
    
    translation_table = dict((ord(ic), oc) for ic, oc in zip(in_alphabet, out_alphabet))
    
    print first.translate(translation_table)
    

    It can be extended to uppercase letters as needed.

    0 讨论(0)
提交回复
热议问题