Julius Caesar Cipherプログラムを作成しようとしていますが、文の先頭と末尾にランダムな文字を追加してねじれを加えようとしています。何らかの理由で長い文字列を入力すると、文字列の一部が印刷時に失われます。私はpython 3を使用しています。誰かがこの問題を解決する方法と、なぜこれが起こっているのか説明できますか?ありがとうPython Julius Caesar暗号プログラム
import random
alpha = 'abcdefghijklmnopqrstuvwxyz'
alphaupper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def encode(cleartext):
global alpha
global alphaupper
words = cleartext
cyphertext = ""
for char in words:
if char in alphaupper:
newpos = (alphaupper.find(char) + 13) % 26
cyphertext += alphaupper[newpos]
elif char in alpha:
newpos = (alpha.find(char) + 13) % 26
cyphertext += alpha[newpos]
else:
cyphertext += char
cyphertext = alpha[random.randrange(len(alpha) - 1)] + cyphertext + alpha[random.randrange(len(alpha) - 1)]
return cyphertext
def decode(cleartext):
global alpha
global alphaupper
words = cleartext.replace(cleartext[len(cleartext) - 1], "")
words = words.replace(words[0], "")
cyphertext = ""
for char in words:
if char in alphaupper:
newpos = (alphaupper.find(char) + 13) % 26
cyphertext += alphaupper[newpos]
elif char in alpha:
newpos = (alpha.find(char) + 13) % 26
cyphertext += alpha[newpos]
else:
cyphertext += char
return cyphertext
print("Julias Ceasar 13 letter shift")
def men():
words = input("Would you like to decode or encode: ")
if "decode" in words:
words = input("What would you like to decode: ")
print(decode(words))
print('\n')
men()
elif "encode" in words:
words = input("What would you like to encode: ")
print(encode(words))
print('\n')
men()
else:
print("Could not understand please try again")
print('\n')
men()
if __name__ == "__main__":
men()
OUTPUT:
Julias Ceasar 13 letter shift
Would you like to decode or encode: encode
What would you like to encode: This program deletes parts of this string for some reason
ENCODED:
yGuvf cebtenz qryrgrf cnegf bs guvf fgevat sbe fbzr ernfbas
DECODING:
Would you like to decode or encode: decode
What would you like to decode: yGuvf cebtenz qryrgrf cnegf bs guvf fgevat sbe fbzr ernfbas
最終的な復号SENTENCE:
This program deletes parts o this string or some reason
Would you like to decode or encode:
注:rot13のポイントは、同じエンコードとデコード機能を必要としない点です。パディング文字を追加/削除するなどの作業を行っても、コードの重複を取り除き、バグの可能性を減らし、コードをより保守しやすくするために、rot13部分を別の方法に分解してください。 –
エンコーディングを除いて、デコードするのが少し難しくなるように、最初と最後に余分な文字を追加する。デコード時に1つの関数であると想定された場合、余分な文字を削除して元の文字列にデコードする代わりに、余分な文字を追加して過去の文字列をデコードします。 – RafaelPiloto10
"もしそれが1つの関数であるとすれば" - それは1つの関数にあるとは思われません。 1つの機能ですべてを行う必要はありません(おそらく教室外の課題やパズル以外)。問題の[分解](https://en.wikipedia.org/wiki/Decomposition_(computer_science))をより細かく調べて、まだ維持可能な大きなプログラムを構築することは良いことです。 –