2016年6月9日木曜日

開発環境

Think Python (Allen B. Downey (著)、 O'Reilly Media)のChapter 8.(Strings)のExercises 8-5(No. 1915)を取り組んでみる。

Exercises 8-5(No. 1915)

コード(Emacs)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

def rotate_word(word, n):
    result = ''
    for ch in word:
        code = ord(ch)
        m = code + n
        if ch.islower():
            if m < ord('a'):
                result += chr(ord('z') + 1 + m - ord('a'))
            elif ord('z') < m:
                result += chr(ord('a') - 1 + m - ord('z'))
            else:
                result += chr(m)
        elif ch.isupper():
            if m < ord('A'):
                resutl += chr(ord('Z') + 1 + ord('A') - m)
            elif ord('Z') < m:
                result += chr(ord('A') - 1 + m - ord('Z'))
            else:
                result += chr(m)
        else:
            result += chr(code)
    return result


if __name__ == '__main__':
    print('cheer: {0}'.format(rotate_word('cheer', 7)))
    print('IBM: {0}'.format(rotate_word('IBM', -1)))
    for word in [r + o + t + '13' for r in 'rR' for o in 'oO' for t in 'tT']:
        word0 = rotate_word(rotate_word(word, 13), 13)
        print('{0}: {1} {2}'.format(word, word0, word == word0))

入出力結果(Terminal, IPython)

$ ./rotate.py
cheer: jolly
IBM: HAL
rot13: rot13 True
roT13: roT13 True
rOt13: rOt13 True
rOT13: rOT13 True
Rot13: Rot13 True
RoT13: RoT13 True
ROt13: ROt13 True
ROT13: ROT13 True
$

0 コメント:

コメントを投稿