我在试图找出如何让我的解密功能工作时遇到了很多麻烦。它适用于msg可以被3整除的理想情况,但之后我完全迷失了。我对我必须做的事情有一个模糊的想法,因为我能够使用两个轨道来实现这一点,但是有三个轨道的可能性更大。我很丢失:(所有那些印刷声明只是试图帮我弄清楚发生了什么。
import sys
def main():
plaintext="abcdefgh"
print(threeRailEncrypt(plaintext))
print(threeRailDecrypt(threeRailEncrypt(plaintext)))
def threeRailEncrypt(plaintext):
ciphertext=""
rail1=""
rail2=""
rail3=""
for i in range(len(plaintext)):
if i%3 == 0:
rail1=rail1+plaintext[i]
elif i%3 == 1:
rail2=rail2+plaintext[i]
else:
rail3=rail3+plaintext[i]
ciphertext=rail1+rail2+rail3
return(ciphertext)
def threeRailDecrypt(msg):
if len(msg)%3==0:
third=len(msg)//3
print(third)
rail1=msg[:third]
rail2=msg[third:third*2]
rail3=msg[third*2:]
print(rail1,rail2,rail3)
dm=""
for i in range(third):
dm=dm+rail1[i]
dm=dm+rail2[i]
dm=dm+rail3[i]
else:
third=(len(msg)//3)+1
print(third)
rail1=msg[:third]
rail2=msg[third:third*2]
rail3=msg[third*2:]
print(rail1,rail2,rail3)
dm=""
for i in range(third):
dm=dm+rail1[i]
print(dm)
dm=dm+rail2[i]
print(dm)
dm=dm+rail3[i]
print(dm)
if len(rail2)>len(rail3):
dm=dm+rail2[-1]
return(dm)
main()
答案 0 :(得分:2)
您可以使用步幅切割字符串(或任何其他序列);您可以选择每个第3个字符:
def threeRailEncrypt(plaintext):
return plaintext[::3] + plaintext[1::3] + plaintext[2::3]
要扭转趋势,请将密文分成三个块并使用itertools.zip_longest()
重新组合它们:
from itertools import zip_longest, chain
def threeRailDecrypt(ciphertext):
stride, remainder = divmod(len(ciphertext), 3)
# how large was each of the three sections?
sizes = [stride] * 3
for i in range(remainder):
sizes[i] += 1
# slice ciphertext up into 3 sections again
pos = 0
pieces = []
for s in sizes:
pieces.append(ciphertext[pos:pos + s])
pos += s
# recombine the triplets
return ''.join(chain.from_iterable(zip_longest(*pieces, fillvalue='')))
演示:
>>> threeRailEncrypt('Foo bar baz and all')
'F raa lob znaoab dl'
>>> threeRailDecrypt(threeRailEncrypt('Foo bar baz and all'))
'Foo bar baz and all'
没有zip_longest
的最后一部分将是:
# recombine the triplets
plaintext = []
for i in range(len(parts[0])):
for part in parts:
try:
plaintext.append(part[i])
except IndexError: # part too short
pass
return ''.join(plaintext)