Pytm:
入力文字列はアルファベットのみで構成されます。この関数はすべての文字がアルファベットで2つのスポット「UP」に移動されている文字列を返す必要があります。
例えば:
- 「」「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(""))
schwobaseggl:
いくつかのutilsのは有益です。あなたはこの関数を繰り返し使用する場合は、常に、インデックス、それゆえ参照を見つけるために、文字を反復処理する必要はありません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'