Practical Programming
An Introduction to Computer Science
Using Python 3
(Pragmatic Programmers)
(Pragmatic Bookshelf)
Paul Gries (著) Jennifer Campbell (著)
Jason Montojo (著) Lynn Beighley (編集)
開発環境
- OS X Mavericks - 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) 2-a, b, c.を解いてみる。
12.4(Exercises) 2-a, b, c.
コード(BBEdit)
sample2.py
#!/usr/bin/env python3 #-*- coding: utf-8 -*- # a, b. def minIndex(l): ''' >>> minIndex([9, 0, 8, 1, 7, 2, 7, 3, 5]) (0, 1) ''' i = 0 v = l[0] for x in range(1, len(l)): if l[x] < v: i = x v = l[x] return (v, i) def minOrMaxIndex(l, flag=True): ''' >>> minOrMaxIndex([9, 0, 8, 1, 7, 2, 7, 3, 5]) (0, 1) >>> minOrMaxIndex([9, 0, 8, 1, 7, 2, 7, 3, 5], flag=True) (0, 1) >>> minOrMaxIndex([9, 0, 8, 1, 7, 2, 7, 3, 5], flag=False) (9, 0) ''' if flag: return minIndex(l) i = 0 v = l[0] for x in range(1, len(l)): if l[x] > v: i = x v = l[x] return (v, i) if __name__ == '__main__': import doctest doctest.testmod() import random l = [random.randrange(100) for x in range(10)] print('{0}: {1}, {2}'.format( l, minOrMaxIndex(l), minOrMaxIndex(l, flag=False)))
入出力結果(Terminal, IPython)
$ ./sample2.py -v Trying: minIndex([9, 0, 8, 1, 7, 2, 7, 3, 5]) Expecting: (0, 1) ok Trying: minOrMaxIndex([9, 0, 8, 1, 7, 2, 7, 3, 5]) Expecting: (0, 1) ok Trying: minOrMaxIndex([9, 0, 8, 1, 7, 2, 7, 3, 5], flag=True) Expecting: (0, 1) ok Trying: minOrMaxIndex([9, 0, 8, 1, 7, 2, 7, 3, 5], flag=False) Expecting: (9, 0) ok 1 items had no tests: __main__ 2 items passed all tests: 1 tests in __main__.minIndex 3 tests in __main__.minOrMaxIndex 4 tests in 3 items. 4 passed and 0 failed. Test passed. [46, 79, 2, 38, 84, 64, 55, 87, 57, 13]: (2, 2), (87, 7) $
0 コメント:
コメントを投稿