👩💻
言語処理100本ノック 2020 (Rev 2) 第1章: 準備運動 08. 暗号文
問題
08. 暗号文
与えられた文字列の各文字を,以下の仕様で変換する関数cipherを実装せよ.
- 英小文字ならば(219 - 文字コード)の文字に置換
- その他の文字はそのまま出力
この関数を用い,英語のメッセージを暗号化・復号化せよ.
solution08.py
def cipher(s: str) -> str:
# 変換後の文字列を格納する変数
result = ""
# 文字列 s の各文字を処理する
for c in s:
# 英小文字の場合は変換する
if c.islower():
result += chr(219 - ord(c))
# その他の文字はそのまま出力する
else:
result += c
return result
# 暗号化
encrypted = cipher("Hello, World!")
print(encrypted) # => Hvww, Dqgry!
# 復号化
decrypted = cipher(encrypted)
print(decrypted) # => Hello, World!
output
Hvool, Wliow!
Hello, World!
この問題では、PythonでUnicodeコードポイント(文字コード)と文字を相互に変換するには組み込み関数chr()
, ord()
を使います。
あるUnicodeコードポイントの文字を取得するにはchr()
、ある文字のUnicodeコードポイントを取得するにはord()
を使います。
参考記事
第1章: 準備運動
PythonでUnicodeコードポイントと文字を相互変換(chr, ord, \x, \u, \U)
unicodeとは?文字コードとは?UTF-8とは?
Discussion