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 15(Testing and Debugging)、15.7(Exercises) 2.を解いてみる。
15.7(Exercises) 2.
コード(BBEdit)
sample2.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import unittest
def lineIntersect(line1, line2):
p1, p2 = line1
p3, p4 = line2
p1x, p1y = p1
p2x, p2y = p2
p3x, p3y = p3
p4x, p4y = p4
x1 = p2x - p1x
y1 = p2y - p1y
x2 = p4x - p3x
y2 = p4y - p3y
if x1 == 0:
a1 = None
else:
a1 = y1 / x1
if x2 == 0:
a2 = None
else:
a2 = y2 / x2
if a1 == None and a2 == None:
if p1x == p3x:
return line1
else:
return None
if a1 == None:
return [p1x, a2 * p1x + (p3y - a2 * p3x)]
if a2 == None:
return [a1 * p3x + (p1y - a1 * p1x), p3x]
k1 = p1y - a1 * p1x
k2 = p3y - a2 * p3x
if a1 == a2:
if k1 == k2:
return line1
else:
return None
x = (k2 - k1) / (a1 - a2)
y = a1 * x + k1
return [x, y]
class TestLineIntersect(unittest.TestCase):
def test_not_intersect(self):
line1 = [[0, 0], [1, 1]]
line2 = [[0, 1], [1, 2]]
expected = None
actual = lineIntersect(line1, line2)
self.assertEqual(expected, actual)
def test_not_intersect1(self):
line1 = [[0, 0], [1, 0]]
line2 = [[0, 1], [1, 1]]
expected = None
actual = lineIntersect(line1, line2)
self.assertEqual(expected, actual)
def test_not_intersect2(self):
line1 = [[0, 0], [0, 1]]
line2 = [[1, 0], [1, 1]]
expected = None
actual = lineIntersect(line1, line2)
self.assertEqual(expected, actual)
def test_intersect(self):
line1 = [[0, 0], [1, 1]]
line2 = [[0, 1], [1, 0]]
expected = [0.5, 0.5]
actual = lineIntersect(line1, line2)
self.assertEqual(expected, actual)
def test_coincident(self):
line1 = [[0, 0], [1, 1]]
line2 = [[0, 0], [-1, -1]]
expected = line1
actual = lineIntersect(line1, line2)
self.assertEqual(expected, actual)
def test_coincident1(self):
line1 = [[0, 0], [-1, -1]]
line2 = [[0, 0], [1, 1]]
expected = line1
actual = lineIntersect(line1, line2)
self.assertEqual(expected, actual)
if __name__ == '__main__':
unittest.main()
入出力結果(Terminal, IPython)
$ ./sample2.py ...... ---------------------------------------------------------------------- Ran 6 tests in 0.002s OK $
0 コメント:
コメントを投稿