python - Python:如何反转字符串的多个切片操作
问题描述
我正在研究一个有趣的 Python 编码问题:
从字符串中取出每个第二个字符,然后是不是每个第二个字符的其他字符,并将它们连接为新字符串。这样做n次!
例如:
"这是一个测试!", 1 -> "hsi etTi sats!" "这是一个测试!", 2 -> "hsi etTi sats!" -> “s eT ashi tist!”
我写的函数是:
def encrypt(text, n):
if n <= 0:
return text
else:
a = encrypt(text, n-1)[1::2]
b = encrypt(text, n-1)[::2]
return a+b
测试功能的结果表明这似乎有效。但现在我不知道如何扭转这个动作。例如,使用 ("hsi etTi sats!", 1) 作为输入,我应该如何操作它以使其恢复为“这是一个测试!”?我知道如何获取列表中的所有其他字符,但你如何将它们放回去。我仍处于学习 Python 的早期阶段,所以我想这是由于我对某些基础知识的知识存在漏洞。
String = "ABCDEF"
a= String[1::2] = "BDF"
b= String[::2] ="ACE"
您如何操作 a 和 b 以便可以恢复 String?我不确定我是否已经澄清了自己。
提前感谢您的时间。
解决方案
其他一些答案缺少完整问题的两个重要方面
- 当字符数为奇数时会发生什么?
zip
如果您或map
长度不等的序列,最后一个字符将丢失。 - 那么递归加密呢?
所以这是你的解密功能:
def encrypt(text, n):
if n <= 0:
return text
else:
a = encrypt(text, n-1)[1::2]
b = encrypt(text, n-1)[::2]
return a+b
def decrypt(text, n):
if n <= 0:
return text
else:
a, b = text[:len(text)//2], text[len(text)//2:]
text = "".join(map(lambda x, y: x + y, b, a))
text = decrypt(text, n-1)
if len(b) > len(a):
# happens for odd number of characters. We need to append last from b
text += b[-1]
return text
s = "This is a test!"
print("n=1: {0}".format(decrypt(encrypt(s, 1), 1)))
print("n=2: {0}".format(decrypt(encrypt(s, 2), 2)))
print("n=3: {0}".format(decrypt(encrypt(s, 3), 3)))
>>> n=1: This is a test!
>>> n=2: This is a test!
>>> n=3: This is a test!
推荐阅读
- css - 将图标拉到右侧并与文本内联?
- javascript - 关闭按钮旁边的模态标题中的浮动按钮
- python - LIBSVM 精度错误:精度为零
- python - 基于选定用户的 Twitter 情绪分析
- ruby-on-rails - 如何重新加载rails环境?`reload!` 命令是否已弃用?
- reactjs - 使用 React.cloneElement 时如何将道具传递给样式组件
- ios - 在 SwiftUI 中完成动画后隐藏和显示视图
- reactjs - Adsense 不会批准我的 reactjs 应用程序,有什么解决方法吗?
- angular - 数组第一次没有填充
- excel - 从范围中提取数据的 Excel 输入字段