我正在编写一个加密程序,其过程如下:
- 消息中的空格替换为
'X'
's - 原始消息中的每个单词都颠倒了
- 连续的单词序列,称为“块”,单词的顺序是颠倒的。这些块的大小是加密函数的参数,充当“密钥”。例如,如果消息是
'THE PRICE OF FREEDOM IS ETERNAL VIGILENCE'
并且块大小为 4,则每个四个字的块将被反转,产生'FREEDOM OF PRICE THE VIGILENCE ETERNAL IS'
(忽略上面的其他两个步骤)。请注意,在这种情况下,最后一个块只有三个单词,但它仍然是颠倒的。
现在我已经能够替换空格并反转所有内容,但最后一步让我感到难过。
以下代码是我到目前为止所拥有的。
def encrypt (words, block):
words = words [::-1]
midpoint = len(words)/block
first_half = words[0:midpoint]
second_half = words[midpoint:]
words = first_half + second_half
words = words.replace(' ', 'X')
return words
def decrypt (wordsde, block):
wordsde = wordsde[::-1]
midpoint = len(wordsde) / block
first_half = wordsde[:midpoint]
second_half = wordsde[midpoint:]
wordsde = first_half + second_half
wordsde = wordsde.replace('X', ' ')
wordsde = wordsde.strip()
return wordsde
但每次,它都无法读取块或其他东西:
File "__main__", line 18, in __main__
Failed example:
encrypt('WHO WATCHES THE WATCHERS', 2) # Test 4
Expected:
'SEHCTAWXOHWXSREHCTAWXEHT'
Got:
'SREHCTAWXEHTXSEHCTAWXOHW'
Trying:
encrypt('PARANOIA IS OUR PROFESSION', 3) # Test 5
Expecting:
'RUOXSIXAIONARAPXNOISSEFORP'
**********************************************************************
File "__main__", line 22, in __main__
Failed example:
encrypt('PARANOIA IS OUR PROFESSION', 3) # Test 5
Expected:
'RUOXSIXAIONARAPXNOISSEFORP'
Got:
'NOISSEFORPXRUOXSIXAIONARAP'
Trying:
encrypt('THE PRICE OF FREEDOM IS ETERNAL VIGILENCE', 4) # Test 6
Expecting:
'MODEERFXFOXECIRPXEHTXECNELIGIVXLANRETEXSI'
**********************************************************************
File "__main__", line 26, in __main__
Failed example:
encrypt('THE PRICE OF FREEDOM IS ETERNAL VIGILENCE', 4) # Test 6
Expected:
'MODEERFXFOXECIRPXEHTXECNELIGIVXLANRETEXSI'
Got:
'ECNELIGIVXLANRETEXSIXMODEERFXFOXECIRPXEHT'