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 13(Searching and Sorting)、13.7(Exercises) 9.を解いてみる。
13.7(Exercises) 9.
コード(BBEdit)
sample9.py
#!/usr/bin/env python3 #-*- coding: utf-8 -*- def merge1(l1, l2): '''(list, list) -> list >>> merge1([1, 3, 4, 6], [1, 2, 5, 7]) [1, 1, 2, 3, 4, 5, 6, 7] ''' new_l = [] i1 = 0 i2 = 0 while 0 <= i1 < len(l1) and 0 <= i2 < len(l2): if l1[i1] <= l2[i2]: new_l.append(l1[i1]) i1 += 1 else: new_l.append(l2[i2]) i2 += 1 new_l.extend(l1[i1:]) new_l.extend(l2[i2:]) return new_l def merge2(l1, l2): '''(list, list) -> list >>> merge2([1, 3, 4, 6], [1, 2, 5, 7]) [1, 1, 2, 3, 4, 5, 6, 7] ''' new_l = [] i1 = 0 i2 = 0 while not (i1 == len(l1) or i2 == len(l2)): if l1[i1] <= l2[i2]: new_l.append(l1[i1]) i1 += 1 else: new_l.append(l2[i2]) i2 += 1 new_l.extend(l1[i1:]) new_l.extend(l2[i2:]) return new_l if __name__ == '__main__': import doctest doctest.testmod()
入出力結果(Terminal, IPython)
$ ./sample9.py -v Trying: merge1([1, 3, 4, 6], [1, 2, 5, 7]) Expecting: [1, 1, 2, 3, 4, 5, 6, 7] ok Trying: merge2([1, 3, 4, 6], [1, 2, 5, 7]) Expecting: [1, 1, 2, 3, 4, 5, 6, 7] ok 1 items had no tests: __main__ 2 items passed all tests: 1 tests in __main__.merge1 1 tests in __main__.merge2 2 tests in 3 items. 2 passed and 0 failed. Test passed. $
0 コメント:
コメントを投稿