2019年8月20日火曜日

開発環境

Head First はじめてのプログラミング ―頭とからだで覚えるPythonプログラミング入門 (Eric Freeman(著)、嶋田 健志(監修)、木下 哲也(翻訳)、株式会社オライリー・ジャパン)を12章(オブジェクト指向プログラミング - オブジェクト村への旅)のエクササイズ(540ページ)の解答を求めてみる。

コード

Python 3

#!/usr/bin/env python3
from unittest import TestCase, main
from typing import List


class PalindromeStringTest(TestCase):
    def setUp(self):
        pass

    def tearDown(self):
        pass

    def test_is_palindrome(self):
        words = [PalindromeString('radar'),
                 PalindromeString('rader')]
        lengths = [5, 5]
        uppercases = ['RADAR', 'RADER']
        blns = [True, False]
        for word, length, uppercase, bln in zip(words,
                                                lengths,
                                                uppercases,
                                                blns):
            self.assertEqual(len(word), length)
            self.assertEqual(word.upper(), uppercase)
            self.assertEqual(word.is_palindrome(), bln)


class PalindromeString(str):
    def is_palindrome(self) -> bool:
        i = 0
        j = len(self) - 1
        while i < j:
            if self[i] != self[j]:
                return False
            i += 1
            j -= 1
        return True


if __name__ == '__main__':
    main()

入出力結果(Bash、cmd.exe(コマンドプロンプト)、Terminal、Jupyter(IPython))

$ ./sample3.py
E
======================================================================
ERROR: test_is_palindrome (__main__.PalindromeStringTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "./sample3.py", line 14, in test_is_palindrome
    words = [PalindromeString('radar'),
NameError: name 'PalindromeString' is not defined

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (errors=1)
$ ./sample3.py
F
======================================================================
FAIL: test_is_palindrome (__main__.PalindromeStringTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "./sample3.py", line 25, in test_is_palindrome
    self.assertEqual(word.is_palindrome, bln)
AssertionError: <bound method PalindromeString.is_palindrome of 'radar'> != True

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (failures=1)
$ ./sample3.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK
$ 

0 コメント:

コメントを投稿