输入字符串将只包含字母字符。该函数应该返回一个字符串,在该字符串中,所有字符都被移动到字母表中的两个位置。
例如:
我写了这段代码,但我觉得太长了。我怎样才能使它更短更好呢?
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(""))发布于 2020-03-28 16:12:35
一些功用将是有益的。如果您反复使用此函数,则不总是希望迭代字符来查找索引,因此需要查找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'发布于 2020-03-28 16:04:19
您可以使用itertools.islice和itertools.cycle获得下一个字符(即向前两个位置):
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])发布于 2020-03-28 15:59:12
您可以做两个改进:
使用字符串模块获取字母
)
1
%)简化计算(25 + 2) % 26计算为
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_shttps://stackoverflow.com/questions/60902982
复制相似问题