Pythagorean Theorem
The goal of incremental development is to avoid long debugging. By Pythagorean Theorem, the distance between two points is: \[d = \sqrt{(x2-x1)^2 + (y2-y1)^2} \]Step 1
""" Step 1 / Incremental Development
Define the function, with wrong answer but syntactically correct
"""
def distance(x1, y1, x2, y2):
return 0.0
assert distance(1, 2, 4, 6) == 0.0
assert distance(1, 2, 1, 2) == 0.0
print("Asserts passed!")
Step 2
""" Step 2 / Incremental Development
Find the differences x2-x1, y2-y1
"""
def distance(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
return 0.0
assert distance(1, 2, 4, 6) == 0.0
assert distance(1, 2, 1, 2) == 0.0
print("Asserts passed!")
Step 3
""" Step 3 / Incremental Development
Compute the sum of squares
"""
def distance(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
sum = dx**2 + dy**2
return 0.0
assert distance(1, 2, 4, 6) == 0.0
assert distance(1, 2, 1, 2) == 0.0
print("Asserts passed!")
Step 4
""" Step 4 / Incremental Development
Finally, use math.sqrt() to compute the result
"""
import math
def distance(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
sum = dx**2 + dy**2
return math.sqrt(sum)
d = distance(1, 2, 4, 6)
assert distance(1, 2, 4, 6) == 5.0
assert distance(2, 2, 2, 6) == 4.0
print("Asserts passed!")
Last update: 77 days ago