2013年12月24日火曜日

開発環境

初めてのコンピュータサイエンス(Jennifer CampbellPaul GriesJason MontojoGreg Wilson(著)長尾 高弘(翻訳))の12章(各種ツール)、12.7(練習問題)、12-20.を解いてみる。

12.7(練習問題)、12-20.

コード(BBEdit)

sample.py

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

import nose

def findButNotAfter(source, prefix, pattern):
    '''sourceの中で最初にpatternが現れた位置(ただし直前がprefixになっていてはなりま
    せん)の添字をかえします。また、sourceの中でpatternが現れない場合、patternが空文字
    の場合、prefixが空文字の場合、patternの直前が常にprefixの場合はNoneを返します。
    例えば、findButNotAfter('abcdcd', 'ab', 'cd')は、4を返します。最初のcdは直前に
    aがあるので条件を満たさないのです。しかし、
    findButNotAfter('abxcdcd', 'ab', 'cd')なら3を返します。'''
    if pattern == '' or prefix == '':
        return None
    start = 0
    result = source.find(pattern)
    while result != -1:
        if source[result - len(prefix):result] != prefix:
            break
        else:
            start = result + 1
            result = source.find(pattern, start)
    if result == -1:
        return None
    return result

def test_allEmpty():
    assert findButNotAfter('', '', '') == None

def test_sourceAndPrefixEmpty():
    assert findButNotAfter('', '', 'a') == None

def test_sourceAndPatternEmpty():
    assert findButNotAfter('', 'a', '') == None

def test_patternAndPrefixEmpty():
    assert findButNotAfter('a', '', '') == None

def test_sourceEmpty():
    assert findButNotAfter('', 'a', 'b') == None

def test_patternEmpty():
    assert findButNotAfter('a', '', 'b') == None

def test_prefixEmpty():
    assert findButNotAfter('a', 'a', '') == None

def test_notFind():
    assert findButNotAfter('abcd', 'a', 'bc') == None

def test_find2():
    assert findButNotAfter('abcdcd', 'ab', 'cd') == 4

def test_find2():
    assert findButNotAfter('abxcdcd', 'ab', 'cd') == 3
        

if __name__ == '__main__':
    nose.runmodule()

入出力結果(Terminal)

$ ./sample.py
.........
----------------------------------------------------------------------
Ran 9 tests in 0.002s

OK
$

0 コメント:

コメントを投稿