2018年12月27日木曜日

開発環境

問題解決のPythonプログラミング ―数学パズルで鍛えるアルゴリズム的思考 (Srini Devadas (著)、黒川 利明 (翻訳)、オライリージャパン)の16章(貪欲は良いことだ)、練習問題(パズル問題2)を取り組んでみる。

コード(Emacs)

Python 3

#!/usr/bin/env python3
def get_courses_after(course: list, courses: list):
    '''
    >>> get_courses_after([9, 12, 3], courses)
    [[12, 13, 1], [15, 16, 1], [16, 17, 1], [18, 20, 2], [17, 19, 2], [13, 20, 7]]
    >>> get_courses_after([17, 19, 2], courses)
    []
    '''
    _, finish, _ = course
    return [c for c in courses if c[0] >= finish]


def get_weight(courses: list) -> int:
    '''
    >>> get_weight(courses)
    19
    '''
    return sum([weight for _, _, weight in courses])


def recursive_select(courses: list) -> list:
    '''
    >>> recursive_select(courses)
    [[9, 12, 3], [12, 13, 1], [13, 20, 7]]
    '''
    if len(courses) == 0:
        return []
    weight = 0
    for course in courses:
        courses_after = get_courses_after(course, courses)
        courses_tmp = [course] + recursive_select(courses_after)
        weight_tmp = get_weight(courses_tmp)
        if weight_tmp > weight:
            weight = weight_tmp
            selected_courses = courses_tmp
    return selected_courses


if __name__ == '__main__':
    import doctest

    courses = [[8, 10, 1], [9, 12, 3], [11, 12, 1], [12, 13, 1], [15, 16, 1],
               [16, 17, 1], [18, 20, 2], [17, 19, 2], [13, 20, 7]]
    globs = globals()
    globs.update({'courses': courses})
    doctest.testmod(globs=globs)

入出力結果(Terminal, cmd(コマンドプロンプト), Jupyter(IPython))

$ ./sample2.py -v
Trying:
    get_courses_after([9, 12, 3], courses)
Expecting:
    [[12, 13, 1], [15, 16, 1], [16, 17, 1], [18, 20, 2], [17, 19, 2], [13, 20, 7]]
ok
Trying:
    get_courses_after([17, 19, 2], courses)
Expecting:
    []
ok
Trying:
    get_weight(courses)
Expecting:
    19
ok
Trying:
    recursive_select(courses)
Expecting:
    [[9, 12, 3], [12, 13, 1], [13, 20, 7]]
ok
1 items had no tests:
    __main__
3 items passed all tests:
   2 tests in __main__.get_courses_after
   1 tests in __main__.get_weight
   1 tests in __main__.recursive_select
4 tests in 4 items.
4 passed and 0 failed.
Test passed.
$

0 コメント:

コメントを投稿

関連コンテンツ