開発環境
- macOS Sierra - Apple (OS)
- Emacs (Text Editor)
- Python 3.5 (プログラミング言語)
Think Python (Allen B. Downey (著)、 O'Reilly Media)のChapter 15.(Classes and Objects)のExercises 15-1.(No. 3559)を取り組んでみる。
Exercises 15-1.(No. 3559)
コード(Emacs)
test
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import unittest
from sample1 import *
class Test(unittest.TestCase):
def setUp(self):
self.point = Point(0, 0)
self.circle = Circle(self.point, 10)
def tearDown(self):
pass
def test_point_in(self):
p = Point(0, 1)
self.assertTrue(point_in_circle(self.circle, p))
def test_point_bound(self):
p = Point(0, 10)
self.assertTrue(point_in_circle(self.circle, p))
def test_point_out(self):
p = Point(11, 0)
self.assertFalse(point_in_circle(self.circle, p))
def test_rect_in(self):
r = Rectangle(1, 2, self.point)
self.assertTrue(rect_in_circle(self.circle, r))
def test_rect_bound(self):
w = 10 * math.cos(math.pi / 4)
h = 2 * 10 * math.sin(math.pi / 4)
p = Point(0, -10 * math.sin(math.pi / 4))
r = Rectangle(w, h, p)
self.assertTrue(rect_in_circle(self.circle, r))
def test_rect_out(self):
r = Rectangle(11, 2, self.point)
self.assertFalse(rect_in_circle(self.circle, r))
def test_rect_overlap(self):
r = Rectangle(1, 2, Point(10, 0))
self.assertTrue(rect_circle_overlap(self.circle, r))
def test_rect_overlap_false(self):
r = Rectangle(1, 2, Point(10.1, 0))
self.assertFalse(rect_circle_overlap(self.circle, r))
if __name__ == '__main__':
unittest.main()
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import math
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class Rectangle:
def __init__(self, width, height, corner):
self.width = width
self.height = height
self.corner = corner
class Circle:
def __init__(self, center, radius):
self.center = center
self.radius = radius
def point_in_circle(circle, point):
return math.sqrt(
(circle.center.x - point.x) ** 2 + (circle.center.y - point.y) ** 2
) <= circle.radius
def rect_in_circle(circle, rect):
p1 = rect.corner
p2 = Point(rect.corner.x, rect.corner.y + rect.width)
p3 = Point(rect.corner.x + rect.width, rect.corner.y + rect.width)
p4 = Point(rect.corner.x + rect.width, rect.corner.y)
return all(map(lambda p: point_in_circle(circle, p),
(p1, p2, p3, p4)))
def rect_circle_overlap(circle, rect):
p1 = rect.corner
p2 = Point(rect.corner.x, rect.corner.y + rect.width)
p3 = Point(rect.corner.x + rect.width, rect.corner.y + rect.width)
p4 = Point(rect.corner.x + rect.width, rect.corner.y)
return any(map(lambda p: point_in_circle(circle, p),
(p1, p2, p3, p4)))
入出力結果(Terminal, IPython)
$ ./test_sample1.py ........ ---------------------------------------------------------------------- Ran 8 tests in 0.003s OK $
0 コメント:
コメントを投稿