LoginSignup
6
1

More than 5 years have passed since last update.

素人の言語処理100本ノック:08

Last updated at Posted at 2016-09-18

言語処理100本ノック 2015の挑戦記録です。環境はUbuntu 16.04 LTS + Python 3.5.2 :: Anaconda 4.1.1 (64-bit)です。過去のノックの一覧はこちらからどうぞ。

第1章: 準備運動

08.暗号文

与えられた文字列の各文字を,以下の仕様で変換する関数cipherを実装せよ.

・英小文字ならば(219 - 文字コード)の文字に置換
・その他の文字はそのまま出力

この関数を用い,英語のメッセージを暗号化・復号化せよ.

出来上がったコード:

main.py
# coding: utf-8


def cipher(target):
    '''文字列の暗号化、復号化
    以下の仕様で文字列を変換する
    ・英小文字ならば(219 - 文字コード)の文字に置換
    ・その他の文字はそのまま出力

    引数:
    target -- 対象の文字列
    戻り値:
    変換した文字列
    '''
    result = ''
    for c in target:
        if c.islower():
            result += chr(219 - ord(c))
        else:
            result += c
    return result


# 対象文字列の入力
target = input('文字列を入力してください--> ')

# 暗号化
result = cipher(target)
print('暗号化:' + result)

# 復号化
result2 = cipher(result)
print('復号化:' + result2)

# 復号化で元に戻っているかチェック
if result2 != target:
    print('元に戻っていない!?')

実行結果:

端末
文字列を入力してください--> I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind .
暗号化:I xlfowm'g yvorvev gszg I xlfow zxgfzoob fmwvihgzmw dszg I dzh ivzwrmt : gsv ksvmlnvmzo kldvi lu gsv sfnzm nrmw .
復号化:I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind .

問題には対象文字列の指示がないので、input()を使って標準入力から受け取るようにしてみました。
 
9本目のノックは以上です。誤りなどありましたら、ご指摘いただけますと幸いです。

6
1
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
1