You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现2轨栅栏密码解密的Python程序(无需使用def函数)

2轨栅栏密码解密方法

解密原理

2轨栅栏密码的加密逻辑是把明文按字符位置的奇偶性分成两组:轨1包含所有偶数位置的字符,轨2包含所有奇数位置的字符,再将轨1拼接在轨2前面得到密文。解密则是逆向操作:

  1. 计算密文的总长度 n。
  2. 将密文拆分为两部分:
    • 第一部分(对应原轨1)长度为 (n + 1) // 2(向上取整,若密文长度为奇数,第一部分比第二部分多1个字符)
    • 第二部分(对应原轨2)长度为 n // 2(向下取整)
  3. 交替从两部分取字符拼接:先取第一部分第1个,再取第二部分第1个,以此类推;若第一部分有剩余字符,直接追加到末尾。

Python解密代码(无函数版)

以下代码无需使用def函数,直接针对题目要求的测试用例实现:

测试用例1:输入"Cmhmtmrooeoeoorw"

# 输入密文
ciphertext = "Cmhmtmrooeoeoorw"
n = len(ciphertext)
# 拆分轨1和轨2
rail1 = ciphertext[:(n + 1) // 2]
rail2 = ciphertext[(n + 1) // 2:]
# 拼接明文
plaintext = ""
for i in range(len(rail2)):
    plaintext += rail1[i] + rail2[i]
# 处理轨1剩余字符
if len(rail1) > len(rail2):
    plaintext += rail1[-1]
print(plaintext)  # 输出: Comehometomorrow

测试用例2:输入"topaesw lyr"

# 输入密文
ciphertext = "topaesw lyr"
n = len(ciphertext)
# 拆分轨1和轨2
rail1 = ciphertext[:(n + 1) // 2]
rail2 = ciphertext[(n + 1) // 2:]
# 拼接明文
plaintext = ""
for i in range(len(rail2)):
    plaintext += rail1[i] + rail2[i]
# 处理轨1剩余字符
if len(rail1) > len(rail2):
    plaintext += rail1[-1]
print(plaintext)  # 输出: two players

通用使用说明

若要解密其他2轨栅栏密码,只需修改代码中的ciphertext变量值即可,核心逻辑保持不变。

内容的提问来源于stack exchange,提问作者Cannon Ahrens

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 17:46:16