Python Caesar Cipher

时间:2014-11-07 00:24:46

标签: python

我需要为Caesar Cipher创建一个代码。我需要使用for循环来检查文本的每个字符,使用ALPHABET,key和String函数找到移位的字符,并将其添加到“encipheredTextSoFar”的末尾。需要帮助,但没有完成,但我被困住了。

编辑:

我终于明白了,这是我的最终代码:

def circularShift(text, key):
    text = text.upper()
    cipher = ""
    for letter in text:
        shifted = ord(letter) + key
        if shifted < 65:
            shifted += 26
        if shifted > 90:
            shifted -= 26
        cipher += chr(shifted)
    return cipher

print (circularShift("MOLLOY", 3))
print (circularShift("PROORB", -3))

4 个答案:

答案 0 :(得分:1)

使用:string.maketrans

进行简单实施
 import string
 upper_case = string.uppercase
 trans = lambda x,n:string.maketrans(x,x[n:]+x[:n])
 def ceaser(text,n):
    print text.upper().translate(trans(upper_case,n))
 ceaser("MOLLOY",3)
 ceaser("HELLO",6)

输出:

PROORB
KHOOR

答案 1 :(得分:0)

  
    

享受。查看代码内的注释。
    快乐的编程。欢迎来到矩阵:)

  

Python源代码:


# setting status default value to 'y'
status = 'y'

# started a while loop until status will change from 'y' to 'n'
while status == 'y':
    # requesting which word to cipher.
    word = str(raw_input("Word: "))
    # how many position to shift each letter
    shift = int(input("Shift: "))
    # added new line to have pretty output
    print

    # declaring cipher variable to be of type list
    cipher = list()
    # iterating trough each character in word
    for item in word:
        # translanting each characher in word to new character
        # and appending it to cipher list
        cipher.append(chr(ord(item)+shift))

    # printing word
    print word
    # printing ciphered word
    print ''.join(cipher)

    print
    # do We need to cipher another word? yes or no?
    status = raw_input("Repeat? [y|n]: ")
    print

输出:


>>> 
Word: HelLo
Shift: 1

HelLo
IfmMp

Repeat? [y|n]: y

Word: AbCdEF
Shift: 2

AbCdEF
CdEfGH

Repeat? [y|n]: y

Word: abc
Shift: -1

abc
`ab

Repeat? [y|n]: y

Word: 456GHh
Shift: -2

456GHh
234EFf

Repeat? [y|n]: n

>>> 

答案 2 :(得分:0)

  

<强>参考书目:
  Kid Snippets:&#34; Math Class&#34; (由孩子们设想) - YouTube http://youtu.be/KdxEAt91D7k
  玛丽有一首小羔羊童谣歌词 - YouTube http://youtu.be/CkRdvGmcCBE
  玛丽有一只小羊羔 - 维基百科,免费的百科全书http://goo.gl/FNEuyd

Python源代码:

  

注意:也适用于负班次号
  注意:如果反向移位,那么我们编码 - 解码消息
  注意:也保留空格

small_chars = [chr(item) for item in range(ord('a'), ord('z')+1)]
upper_chars = [item.upper() for item in small_chars]

def encode_chr(chr_item, is_upper_case):
    '''
    Cipher each chr_item.
    '''
    # setting orig and end order.
    if is_upper_case:
        orig_ord = ord('A')
        end_ord  = ord('Z')
    else:
        orig_ord = ord('a')
        end_ord  = ord('z')

    # calculating shift    
    temp_ord = ord(chr_item)+shift
    # calculating offset order with modulo.
    # char is after end_ord, calculating offset
    num_of_chars = 26
    offset_ord = (temp_ord - end_ord - 1)%num_of_chars
    return chr(orig_ord + offset_ord)

# enable while loop to repeat until status not 'y'
status = 'y'
while status == 'y':
    # enter word to cipher.
    word = raw_input("Word: ")
    # enter char shift
    shift = input("Shift: ")
    print

    # create cipher list variable
    cipher = list()
    # loop trough each char in word
    for chr_item in word:
        # encode just letters.
        # replace non-alfa with underscore: "_"
        if chr_item in upper_chars or chr_item in small_chars:
            # set is_uppser_case to True for upper case chars.
            is_upper_case = (chr_item in upper_chars) and True
            # cipher char.
            temp_chr = encode_chr(chr_item, is_upper_case)
            # append ciphered char to list
            cipher.append(temp_chr)
        elif chr_item is ' ':
            cipher.append(chr_item)
        else:
            cipher.append('_')

    # print word
    print word
    # print ciphered word
    print ''.join(cipher)

    # repeat again for another word?
    status = raw_input("Repeat? [y|n]: ")
    print

测试用例:

>>> 
Word: aAzZ!@
Shift: 1

aAzZ!@
bBaA__
Repeat? [y|n]: y

Word: aAzZ@!
Shift: -1

aAzZ@!
zZyY__
Repeat? [y|n]: y

Word: aAzZ@$
Shift: 27

aAzZ@$
bBaA__
Repeat? [y|n]: y

Word: aAzZ%^
Shift: -27

aAzZ%^
zZyY__
Repeat? [y|n]: n

>>> 

输出:

  

注意:如果反向移位,那么我们编码 - 解码消息

>>>
Word: "Mary Had a Little    Lamb"
Shift: 1

"Mary Had a Little    Lamb"
_Nbsz Ibe b Mjuumf    Mbnc_
Repeat? [y|n]: y

Word: _Nbsz Ibe b Mjuumf    Mbnc_
Shift: -1

_Nbsz Ibe b Mjuumf    Mbnc_
_Mary Had a Little    Lamb_
Repeat? [y|n]: n

>>>

答案 3 :(得分:0)

alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

def encrypt(texted, shifted):
    crypted_message = ''
    for letter in texted:
        if letter in alphabet:
            index_in_alphabet = alphabet.index(letter)
            crypted_message += alphabet[(index_in_alphabet + shifted) % 26]
        else:
            crypted_message += letter
    print(f"message crypté : {crypted_message}")

def decrypt(texted, shifted):
    decrypted_message = ''
    for letter in texted:
        if letter in alphabet:
            index_in_alphabet = alphabet.index(letter)
            decrypted_message += alphabet[(index_in_alphabet - shifted) % 26]
        else:
            decrypted_message += letter
    print(f"message decrypté : {decrypted_message}")

request = 'yes'
while request == 'yes':
    direction = input("Type 'encode' to encrypt, type 'decode' to decrypt : \n")
    while direction != "encode" and direction != "decode":
        print("Entrez soit 'encode' ou 'decode'")
        direction = input("Type 'encode' to encrypt, type 'decode' to decrypt : \n")

    text = input("Type your message:\n").lower()
    shift = int(input("Type the shift number:\n"))
    while shift > 26:
        print("Enterez un chiffre entre 0 et 25")
        shift = int(input("Type the shift number:\n"))

    if direction == 'encode':
        encrypt(texted=text, shifted=shift)
    else:
        decrypt(texted=text, shifted=shift)
    request = input("Type 'yes' if u want go agin . 'no' if else :\n")