2016年6月25日土曜日

開発環境

Think Python (Allen B. Downey (著)、 O'Reilly Media)のChapter 9.(Case Study Word Play)のExercises 9-4(No. 2069)を取り組んでみる。

Exercises 9-4(No. 2069)

コード(Emacs)

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


def is_reversible(age1, age2):
    age1_str = str(age1)
    age2_str = str(age2)
    width = max(len(age1_str), len(age2_str))
    return age1_str.zfill(width) == age2_str.zfill(width)[::-1]


def test(age_daughter, age_mother):
    count = 0
    while age_mother <= 200:
        if is_reversible(age_daughter, age_mother) or \
           is_reversible(age_mother, age_mother + 1):
            count += 1
            if count == 8:
                return age_daughter
        age_daughter += 1
        age_mother += 1
    return -1


if __name__ == '__main__':
    ages = set()
    for age_daughter in range(0, 200):
        for i in range(15, 50):
            age = test(age_daughter, age_daughter + i)
            if age != -1:
                ages.add((i, age))
    for i, age in ages:
        print('{0}: {1}'.format(i, age))

入出力結果(Terminal, IPython)

$ ./sample9.py
18: 79
$

0 コメント:

コメントを投稿