通过块反转句子的单词顺序

时间:2013-03-31 10:46:58

标签: python

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

  • 消息中的空格被'X'
  • 取代
  • 原始邮件中的每个单词都颠倒了
  • 连续的单词序列,称为“块”,具有单词的顺序 逆转。这些块的大小是加密函数的参数并起作用 作为“关键”。例如,如果消息是'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'

1 个答案:

答案 0 :(得分: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