2014年10月22日水曜日

開発環境

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), 1.を解いてみる。

13.7(Exercises), 1.

コード(BBEdit)

sample1.py

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

# while loop
def linearSeardh1(lst, value):
    '''(list, object) -> int
    Return the index of the last occurance of value in lst, or return -1
    if value i not in lst.
    >>> linearSeardh1([2, 5, 1, -3], 5)
    1
    >>> linearSeardh1([2, 4, 2], 2)
    2
    >>> linearSeardh1([2, 5, 1, -3], 4)
    -1
    >>> linearSeardh1([], 5)
    -1
    '''
    i = len(lst) -1

    while i != -1 and lst[i] != value:
        i -= 1

    if i == -1:
        return -1
    else:
        return i

# for loop
def linearSeardh2(lst, value):
    '''(list, object) -> int
    Return the index of the last occurance of value in lst, or return -1
    if value i not in lst.
    >>> linearSeardh2([2, 5, 1, -3], 5)
    1
    >>> linearSeardh2([2, 4, 2], 2)
    2
    >>> linearSeardh2([2, 5, 1, -3], 4)
    -1
    >>> linearSeardh2([], 5)
    -1
    '''
    for i in range(len(lst) - 1, -1, -1):
        if lst[i] == value:
            return i
    return -1

# sentinel search    
def linearSeardh3(lst, value):
    '''(list, object) -> int
    Return the index of the last occurance of value in lst, or return -1
    if value i not in lst.
    >>> linearSeardh3([2, 5, 1, -3], 5)
    1
    >>> linearSeardh3([2, 4, 2], 2)
    2
    >>> linearSeardh3([2, 5, 1, -3], 4)
    -1
    >>> linearSeardh3([], 5)
    -1
    '''
    lst.insert(0, value)

    i = len(lst) - 1
    while lst[i] != value:
        i -= 1
    
    lst.pop(0)

    if i == 0:
        return -1
    else:
        return i - 1

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

入出力結果(Terminal, IPython)

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

0 コメント:

コメントを投稿