minte9
LearnRemember




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} \]

Incremental / Step 1

The first step will be to 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!")

Incremental / Step 2

The next step is to 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!")

Incremental / Step 3

Then we 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!")

Incremental / Step 4

Finally, you can 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: 169 days ago