繁体   English   中英

我怎样才能缩短这个替换密码?

[英]How can I shorten this substitution cipher code?

输入字符串将仅包含字母字符。 该函数应返回一个字符串,其中所有字符都已在字母表中“向上”移动了两个位置。

例如:

  • “a”会变成“c”
  • “z”会变成“b”

我写了这段代码,但我觉得它太长了。 我怎样才能让它更短更好?

def encrypt_message(strings: str) -> str:
    our_al = ["a", "b", "c", "d", "e", "f", "g", "h", "i", 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
              'v', 'w', 'x', 'y', 'z']
    new_s = ""
    for character in strings:
        index = our_al.index(character)
        if index <= 23:
            index += 2
            new_s += our_al[index]
        elif index == 24:
            new_s += our_al[0]
        elif index == 25:
            new_s += our_al[1]

    return new_s


print(encrypt_message("abc"))
print(encrypt_message("xyz"))
print(encrypt_message(""))

一些实用程序将是有益的。 如果您重复使用此函数,您并不总是希望迭代字符以查找索引,因此查找dict

from string import ascii_lowercase as al

index = {c: i for i, c in enumerate(al)}

def encrypt_message(s: str) -> str:
    return ''.join(al[(index[c] + 2) % 26] for c in s)

>>> encrypt_message('xyz')
'zab'

您可以使用itertools.isliceitertools.cycle来获取下一个字符(位于前 2 个位置):

from itertools import islice, cycle
from string import ascii_lowercase

def get_next_2(c):
    index = ascii_lowercase.index(c)
    return next(islice(cycle(ascii_lowercase), index + 2, None))

def encrypt_message(strings):
    return ''.join(map(get_next_2, strings))

如果您喜欢单行解决方案,您可以使用:

from string import ascii_lowercase as al

def encrypt_message(strings):
    return ''.join([al[(al.index(c) + 2) % 26] for c in strings])

您可以进行两项改进:

  • 使用 string 模块获取字母表中的字母
    • string.ascii_lowercase 是所有小写 ASCII 字母的字符串(这里只需要一个可迭代的,不一定是一个列表,所以一个字符串就可以了)
  • 使用模运算符 ( % ) 来简化计算
    • 模数运算符“环绕”计算,因此(25 + 2) % 26计算结果为1
def encrypt_message(strings: str) -> str:
    new_s = ""
    for character in strings:
        if character not in string.ascii_lowercase:
            continue
        index = string.ascii_lowercase.index(character)
        new_index = (index + 2) % len(string.ascii_lowercase)
        new_s += string.ascii_lowercase[new_index]
    return new_s

您还可以将字符转换为它们的 ASCII 值,添加两个并将它们转换回来。

for character in strings:
    if character not in string.ascii_lowercase:
        continue
    index = ord(character) - 96
    new_index = (index + 2) % 26 + 96 # a is 97
return chr(new_index)

暂无
暂无

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

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