gpt4 book ai didi

python - 如何缩短这个替换密码?

转载 作者:行者123 更新时间:2023-12-02 22:38:07 25 4
gpt4 key购买 nike

The input string will consist of only alphabetic characters. The function should return a string where all characters have been moved "up" two spots in the alphabet.

For example:

  • "a" will become "c"
  • "z" will become "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'

关于python - 如何缩短这个替换密码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60902982/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com