| prev | Draft Version 504 (Mon Dec 5 17:02:07 2005) | next |
overlap that calculates the overlap between two rectanglesRect
getLoX, getLoY, getHiX, and getHiYNone if there's no overlapRect is correctoverlap, and see if the output is correctoverlap:
def overlap(left, right):
'''Calculate overlap between two rectangles.'''
loX = max(left.getLoX(), right.getLoX())
hiX = min(left.getHiX(), right.getHiX())
loY = max(left.getLoY(), right.getLoY())
hiY = min(left.getHiY(), right.getHiY())
if (loX >= hiX) or (loY > hiY):
return None
return Rect(loX, loY, loX, hiY)
r1 = Rect(0, 0, 1, 1)
r2 = Rect(2, 2, 3, 3)
result = overlap(r1, r2)
if result == None:
print 'pass'
else:
print 'fail'
pass
r1 = Rect(0, 0, 1, 1)
r2 = Rect(0, 1, 3, 3)
result = overlap(r1, r2)
if result == None:
print 'pass'
else:
print 'fail'
Traceback (most recent call last):
File "overlap.py", line 97, in ?
result = overlap(r1, r2)
File "overlap.py", line 64, in overlap
return Rect(loX, loY, hiX, hiY)
File "overlap.py", line 9, in __init__
assert 0 <= loY < hiY, 'illegal Y coordinates'
AssertionError: illegal Y coordinates
try:
r1 = Rect(0, 0, 1, 1)
r2 = Rect(0, 1, 3, 3)
result = overlap(r1, r2)
if result == None:
print 'pass'
else:
print 'fail'
except Exception, e:
print 'error', e
pass
loX to Rect's constructor twice, rather than loX and hiXloY > hiY instead of loY >= hiYoverlap works when rectangles do overlap try:
r1 = Rect(0, 0, 3, 3)
r2 = Rect(1, 1, 2, 2)
result = overlap(r1, r2)
if result == Rect(1, 1, 2, 2):
print 'pass'
else:
print 'fail'
except Exception, e:
print 'error', e
error name 'overlap' is not defined
Nonedef runTest(left, right, expected):
try:
assert left is not None
assert right is not None
actual = overlap(left, right)
if actual == expected:
return 'pass'
else:
return 'fail'
except Exception, e:
return 'error'
try/except
None as the left or right rectangle is an error in the testdef runTest(left, right, expected):
try:
assert left is not None
assert right is not None
actual = overlap(left, right)
if actual == expected:
return 'pass'
else:
return 'fail'
except Exception, e:
return 'error'
def f(*args) creates a function that takes any number of argumentsvals, then f(*vals) matches the values with f's argumentsvals is (11, 12, 13), then f(*vals) is the same as f(11, 12, 13)runAllTests that takes two arguments:
def runAllTests(func, tests):
pass = fail = error = 0
for testCase in tests:
try:
args, expected = testCase[:-1], testCase[-1]
actual = func(*args)
if actual == expected:
pass += 1
else:
fail += 1
except Exception, e:
error += 1
for (label, count) in (('pass', pass), ('fail', fail), ('error', error)):
print '%s: %4d' % (label, count)
runAllTests(overlap, tests)
"J" appears three times in a string)x = findAll(structure)[0] is almost always wrong| prev | Copyright © 2005, Python Software Foundation. See License for details. | next |