2017-09-07 5 views
0

Ich lerne durch die Einführung in Computer Science Buch von John Zelle Code zu programmieren. Ich stehe bei Übung 5.8 fest. Ich muss diese Lösung irgendwie modifizieren, wo das nächste Zeichen nach "z" "a" ist, um es kreisförmig zu machen. Jede Hilfe wäre toll :)Kodierung/Dekodierung Caesar Cipher Python 3 ASCII

def main(): 
    print("This program can encode and decode Caesar Ciphers") #e.g. if key value is 2 --> word shifted 2 up e.g. a would be c 
    #input from user 
    inputText = input("Please enter a string of plaintext:").lower() 
    inputValue = eval(input("Please enter the value of the key:")) 
    inputEorD = input("Please enter e (to encrypt) or d (to decrypt) ") 
    #initate empty list 
    codedMessage = "" 

    #for character in the string 
    if inputEorD == "e": 
     for ch in inputText: 
      codedMessage += chr(ord(ch) + inputValue) #encode hence plus 
    elif inputEorD =="d": 
      codedMessage += chr(ord(ch) - inputValue) #decode hence minus 
    else: 
     print("You did not enter E/D! Try again!!") 
    print("The text inputed:", inputText, ".Is:", inputEorD, ".By the key of",inputValue, ".To make the message", codedMessage) 

main() 
+2

Tipp: verwenden sie die [Modulo] (https://docs.python.org/3/ Verweis/Ausdrücke.html # binary-arithmetic-operations) -Operator. – glibdud

Antwort

0

Da Sie mit .lower() -case Buchstaben zu tun haben, es ist fair zu wissen, dass ihr ASCII-Bereich [97-122].

Eine gute Möglichkeit, die Verschiebung kreisförmig zu machen wäre jeden Buchstaben mit dem Bereich darstellen [0-25], die von ord(ch) - 97 geschehen ist, und dann den Schlüssel hinzufügen, Modulo dann das Ergebnis mit 26, so wird es (ord(ch) - 97 + key)%26, dann werden wir ein Ergebnis in Reichweite haben [0-25] und fügte hinzu, 97 werden dann bekommen es ist ASCII-Code:

def main(): 
    print("This program can encode and decode Caesar Ciphers") 
    inputText = input("Please enter a string of plaintext:").lower() 
    inputValue = int(input("Please enter the value of the key:")) # use int(), don't eval unless you read more about it 
    inputEorD = input("Please enter e (to encrypt) or d (to decrypt) ") 
    codedMessage = "" 

    if inputEorD == "e": 
     for ch in inputText: 
      codedMessage += chr((ord(ch) - 97 + inputValue)%26 + 97) 
    elif inputEorD =="d": 
      codedMessage += chr((ord(ch) - 97 - inputValue)%26 + 97) 
    else: 
     print("You did not enter E/D! Try again!!") 
    print("The text inputed:", inputText, ".Is:", inputEorD, ".By the key of",inputValue, ".To make the message", codedMessage) 

main() 
+0

Brilliant - danke für die Hilfe zu diesem :) – karan

+0

@karan Froh, zu helfen :). –

Verwandte Themen