2

我正在编写一个加密程序,其过程如下:

  • 消息中的空格替换为'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'
4

1 回答 1

1

这是一个很好回答的问题。

sentence = 'WHO WATCHES THE WATCHERS'
def chunker(seq, size):
    return (seq[pos:pos + size] for pos in xrange(0, len(seq), size)) # Thanks to http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks/434328#434328
def encrypt(phrase,block):
    l = []
    for g in chunker(phrase.split(),block):
         l.extend(i[::-1] for i in reversed(g))
    return 'X'.join(l)

测试时:

>>> encrypt(sentence,2)
'SEHCTAWXOHWXSREHCTAWXEHT'

>>> 'RUOXSIXAIONARAPXNOISSEFORP' == encrypt('PARANOIA IS OUR PROFESSION', 3)
True

# Strings mentioned above and below were your expected answers 
# mentioned in the question

>>> 'MODEERFXFOXECIRPXEHTXECNELIGIVXLANRETEXSI' == encrypt('THE PRICE OF FREEDOM IS ETERNAL VIGILENCE', 4)=
True
于 2013-03-31T11:13:53.517 回答