2014年10月18日土曜日

開発環境

Practical Programming: An Introduction to Computer Science Using Python 3 (Pragmatic Programmers) (Paul Gries (著)、Jennifer Campbell (著)、Jason Montojo (著)、Lynn Beighley (編集)、Pragmatic Bookshelf)のChapter 12(Designing Algorithms)、12.4(Exercises) 4.を解いてみる。

12.4(Exercises) 4.

コード(BBEdit)

sample4.py

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

def findTwoSmallest(l):
    '''
    >>> findTwoSmallest([1, 2])
    (0, 1)
    >>> findTwoSmallest([2, 1])
    (1, 0)
    >>> findTwoSmallest([5, 1, 4, 2, 3])
    (1, 3)
    >>> findTwoSmallest([3, 2, 4, 1, 5])
    (3, 1)
    >>> findTwoSmallest([5, 5])
    (0, 1)
    '''
    
    if l[0] <= l[1]:
        min1 = 0
        min2 = 1
    else:
        min1 = 1
        min2 = 0

    for i in range(2, len(l)):
        if l[i] < l[min1]:
            min2 = min1
            min1 = i
        elif l[min1] < l[i] < l[min2]:
            min2 = i

    return min1, min2

if __name__ == '__main__':
    import doctest
    doctest.testmod()

入出力結果(Terminal, IPython)

$ ./sample4.py -v
Trying:
    findTwoSmallest([1, 2])
Expecting:
    (0, 1)
ok
Trying:
    findTwoSmallest([2, 1])
Expecting:
    (1, 0)
ok
Trying:
    findTwoSmallest([5, 1, 4, 2, 3])
Expecting:
    (1, 3)
ok
Trying:
    findTwoSmallest([3, 2, 4, 1, 5])
Expecting:
    (3, 1)
ok
Trying:
    findTwoSmallest([5, 5])
Expecting:
    (0, 1)
ok
1 items had no tests:
    __main__
1 items passed all tests:
   5 tests in __main__.findTwoSmallest
5 tests in 2 items.
5 passed and 0 failed.
Test passed.
$

0 コメント:

コメントを投稿