如何缩短这个替换密码



输入字符串将仅由字母字符组成。函数应该返回一个字符串,其中所有字符都已被移动";向上";字母表上的两个位置。

例如:

  • "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])

您可以进行两个改进:

  • 使用字符串模块获取字母表中的字母
    • 字符串.ascii_lower是所有小写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)

最新更新