Python Program to Find Distance Between Two Points
distance = ((x2 - x1)**2 + (y2 - y1)**2)**0.5.Examples
How to Think About It
Algorithm
Code
def distance_between_points(x1, y1, x2, y2): distance = ((x2 - x1)**2 + (y2 - y1)**2)**0.5 return distance # Example usage print(distance_between_points(0, 0, 3, 4))
Dry Run
Let's trace the example (0, 0) and (3, 4) through the code
Input points
x1 = 0, y1 = 0, x2 = 3, y2 = 4
Calculate differences
dx = 3 - 0 = 3, dy = 4 - 0 = 4
Calculate distance
distance = sqrt(3**2 + 4**2) = sqrt(9 + 16) = sqrt(25) = 5.0
Return result
distance = 5.0
| Step | dx | dy | distance |
|---|---|---|---|
| Calculate differences | 3 | 4 | |
| Calculate distance | 5.0 |
Why This Works
Step 1: Calculate differences
Subtract the x and y coordinates to find the horizontal and vertical distances between points using dx = x2 - x1 and dy = y2 - y1.
Step 2: Apply Pythagorean theorem
Square the differences and add them: dx**2 + dy**2 gives the square of the distance.
Step 3: Find the distance
Take the square root of the sum using **0.5 to get the actual distance between the points.
Alternative Approaches
import math def distance_between_points(x1, y1, x2, y2): return math.sqrt((x2 - x1)**2 + (y2 - y1)**2) print(distance_between_points(0, 0, 3, 4))
import numpy as np def distance_between_points(p1, p2): return np.linalg.norm(np.array(p2) - np.array(p1)) print(distance_between_points((0, 0), (3, 4)))
Complexity: O(1) time, O(1) space
Time Complexity
The calculation involves a fixed number of arithmetic operations, so it runs in constant time.
Space Complexity
Only a few variables are used to store intermediate results, so space usage is constant.
Which Approach is Fastest?
Using **0.5 or math.sqrt() both run in constant time; numpy adds overhead but is better for many points.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Using **0.5 | O(1) | O(1) | Simple scripts without imports |
| Using math.sqrt | O(1) | O(1) | Clearer code with standard library |
| Using numpy.linalg.norm | O(1) | O(1) | Working with arrays or many points |
**0.5 or math.sqrt() to find the square root in Python.