繁体   English   中英

使用 lambda 使用 rot13 加密/解密?

[英]encrypt/decrypt with rot13 using a lambda?

我需要使用lambda进行加密/解密,但遇到了一些问题。 我的 function create_rot13()不能接收参数,只有我的 lambda 应该。

这是我目前的代码,没有使用任何lambda ,因为我找不到一个(经过几天的环顾)。 怎么把这么几行代码放进去。

def create_rot13(message):
    crypted = ""
    letters = "abcdefghijklmnopqrstuvwxyz"

    for car in message:
        if car in letters:
            num = letters.find(car)
            num = num + 13
            if num >= len(letters):
                num = num - len(letters)
            crypted = crypted + letters[num]
    else:
        crypted = crypted + car

    crypted = crypted[:-1]
    return crypted

print(create_rot13("jbeyq"))
print(create_rot13("world"))

任何人有提示或东西可以帮助我找到解决我的问题的方法吗?

它应该看起来有点像,除了这个 1 只改变一个数字:

def create_rot13():
 my_fonction = lambda x : x + 13
 return my_fonction

coding = create_rot13()
print(coding(4))

如果你想用lambda做,那么你需要用lambda捕获letters变量并使用map 你想要这样的东西:

def encode_rot13(message):
    offset = ord('a')
    result = map(lambda c: chr((ord(c) + 13 - offset) % 26 + offset), message)
    return "".join(result)

我使用chrord所以我们不需要保留所有字母的字符串。 这里的想法是我们得到一个整数来表示任何给定字符的代码点,所以我们可以做一些数学而不是使用find

这是一个简单的(ab)使用codecs模块 (和lambda)。 请注意,您需要编解码器模块,而不是正常调用.encode('rot13')因为您正在进行文本 - >文本编码。

import codecs
rot13 = lambda s: codecs.encode(s, 'rot13')

以下是一些示例用法:

>>> rot13('foo')
'sbb'

这是我的解决方案:

rot13 = lambda m: ''.join(chr(ord(c)+13) if 'a' <= c.lower() < 'n' else chr(ord(c)-13) if 'm' < c.lower() <= 'z' else c for c in m)

我只是在this上使用它,它是 rot13 编码的:

import this
# output
print(rot13(this.s))
# same output

我正在让 lambda 接受一个字符串并返回一个字符串。 我在连接的生成器上执行此操作,并且只旋转非重音字母,无论大小写如何。 我的版本接受旋转长度并将其过滤为 [0-26] 间隔:

rot = lambda n, m: ''.join(chr(ord(c)+n) if 'a' <= c.lower() <= chr(ord('z')-n) else chr(ord(c)+n-26) if chr(ord('z')-n) < c.lower() <= 'z' else c for c in m) if 0 < n < 27 else ''

为了使用它,您需要传递消息和要旋转的字母数。 因此, rot13rot上的部分应用程序相同,例如rot13(message) == rot(13, message) 然后你可以这样定义rot13

rot13 = lambda m: rot(13, m)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM