Practical Programming
An Introduction to Computer Science
Using Python 3
(Pragmatic Programmers)
(Pragmatic Bookshelf)
Paul Gries (著) Jennifer Campbell (著)
Jason Montojo (著) Lynn Beighley (編集)
開発環境
- OS X Yosemite - Apple (OS)
- Emacs (CUI)、BBEdit - Bare Bones Software, Inc. (GUI) (Text Editor)
- Python 3.4 (プログラミング言語)
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) 5.を解いてみる。
12.4(Exercises) 5.
コード(BBEdit)
sample5.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) >>> findTwoSmallest([10]) (0,) >>> findTwoSmallest([]) () ''' if l == []: return () if len(l) == 1: return (0,) 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)
$ ./sample5.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 Trying: findTwoSmallest([10]) Expecting: (0,) ok Trying: findTwoSmallest([]) Expecting: () ok 1 items had no tests: __main__ 1 items passed all tests: 7 tests in __main__.findTwoSmallest 7 tests in 2 items. 7 passed and 0 failed. Test passed. $
0 コメント:
コメントを投稿