0
1

More than 3 years have passed since last update.

Pythonプラクティス: シーザー暗号

Last updated at Posted at 2021-03-15

背景

Pythonで練習して見る。FizzBuzzやれればいいという人もいるが何かないかと思って
提案します。

仕様

前提知識

シーザー暗号を使う。以下Wikipediaによる説明
シーザー暗号は単一換字式暗号の一種であり、平文の各文字を辞書順で3文字分シフトして(ずらして)暗号文とする暗号である。古代ローマの軍事的指導者ガイウス・ユリウス・カエサル(英語読みでシーザー)が使用したことから、この名称がついた。

内容

・ファイルから単語を取得してKeyに辞書型として設定する。Valueは一律 "None"
・辞書内の単語とシーザー暗号のペアがあるものを見つける。見つけた場合は書き出す。
アウトプットイメージ:IBM 1 HAL

実装準備

実装する前に下記のコードは大いに流用して良いとする。


from __future__ import print_function, division


def rotate_letter(letter, n):
    """Rotates a letter by n places.  Does not change other chars.
    letter: single-letter string
    n: int
    Returns: single-letter string
    """
    if letter.isupper():
        start = ord('A')
    elif letter.islower():
        start = ord('a')
    else:
        return letter

    c = ord(letter) - start
    i = (c + n) % 26 + start
    return chr(i)


def rotate_word(word, n):
    """Rotates a word by n places.
    word: string
    n: integer
    Returns: string
    """
    res = ''
    for letter in word:
        res += rotate_letter(letter, n)
    return res


if __name__ == '__main__':
    print(rotate_word('cheer', 7))
    print(rotate_word('melon', -10))
    print(rotate_word('sleep', 9))

def make_word_dict():
    """Read the words in words.txt and return a dictionary
    that contains the words as keys"""
    d = dict()
    fin = open('words.txt')
    for line in fin:
        word = line.strip().lower()
        d[word] = None
    return d

実装例

def rotate_word(word, n):
    """Rotates a word by n places.
    word: string
    n: integer
    Returns: string
    """
    res = ''
    for letter in word:
        res += rotate_letter(letter, n)
    return res

def rotate_letter(letter, n):
    """Rotates a letter by n places.  Does not change other chars.
    letter: single-letter string
    n: int
    Returns: single-letter string
    """
    if letter.isupper():
        start = ord('A')
    elif letter.islower():
        start = ord('a')
    else:
        return letter

    c = ord(letter) - start
    i = (c + n) % 26 + start
    return chr(i)


def make_word_dict():
    """Read the words in words.txt and return a dictionary
    that contains the words as keys"""
    d = dict()
    fin = open('words.txt')
    for line in fin:
        word = line.strip().lower()
        d[word] = None

    return d

def rotate_pair():

    dList= make_word_dict()
    for c in dList:
        for i in range(1, 14):
            if rotate_word(c, i) in dList:
                print(c,i,rotate_word(c, i))
    return list

if __name__ == '__main__':
        rotate_pair()

追加エクササイズ

辞書型からリスト型に変更して見る。

def make_word_dict():
    """Read the words in words.txt and return a dictionary
    that contains the words as keys"""
    sampleList = []
    fin = open('words.txt')
    for line in fin:
        word = line.strip().lower()
        sampleList.append(word)

    return sampleList

著作権関係

Allen Downey氏作のコードを多いに参考にしました。
"""This module contains a code example related to
Think Python, 2nd Edition
by Allen Downey
http://thinkpython2.com
Copyright 2015 Allen Downey
License: http://creativecommons.org/licenses/by/4.0/

0
1
0

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
0
1