首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何缩短这个替换密码?

如何缩短这个替换密码?
EN

Stack Overflow用户
提问于 2020-03-28 15:46:39
回答 4查看 85关注 0票数 0

输入字符串将只包含字母字符。该函数应该返回一个字符串,在该字符串中,所有字符都被移动到字母表中的两个位置。

例如:

  • "a“将成为"c"
  • "z”将成为"b"

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

代码语言:javascript
复制
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(""))
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2020-03-28 16:12:35

一些功用将是有益的。如果您反复使用此函数,则不总是希望迭代字符来查找索引,因此需要查找dict

代码语言:javascript
复制
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'
票数 2
EN

Stack Overflow用户

发布于 2020-03-28 16:04:19

您可以使用itertools.isliceitertools.cycle获得下一个字符(即向前两个位置):

代码语言:javascript
复制
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))

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

代码语言:javascript
复制
from string import ascii_lowercase as al

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

Stack Overflow用户

发布于 2020-03-28 15:59:12

您可以做两个改进:

使用字符串模块获取字母

  • string.ascii_lowercase是所有小写ASCII字母的字符串(这里只需要一个可迭代的字符串,不一定是一个列表,所以字符串是fine)

)

1

  • 使用模数运算符(%)简化计算
  • 模数运算符“环绕”计算,因此(25 + 2) % 26计算为

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60902982

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档