Every nearest-neighbour method starts by measuring how far apart two examples are. Compute both common distances.
What to build
A program that prints the Euclidean and Manhattan distances between two points with any number of features.
Requirements
- Print
euclidean Eandmanhattan M, each with 4 decimal places.
Input
Two lines, each with the same number of coordinates.
Output
Two lines.
Constraints
1 to 100 coordinates.
Example
Input:
0 0
3 4
Output:
euclidean 5.0000
manhattan 7.0000
Why it works
The Euclidean distance is the straight line between the points (Pythagoras in any number of dimensions); the Manhattan distance walks along each axis in turn.
Examples
Example 1 · Input
0 0 3 4
Expected output
euclidean 5.0000 manhattan 7.0000
Example 2 · Input
1 2 3 1 2 3
Expected output
euclidean 0.0000 manhattan 0.0000
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Pair up the coordinates with `zip`.
Hint 2
Euclidean: square root of the sum of squared differences. Manhattan: sum of absolute differences.
Solution
Show one correct solution (try it yourself first)
a = list(map(float, input().split()))
b = list(map(float, input().split()))
euclidean = sum((x - y) ** 2 for x, y in zip(a, b)) ** 0.5
manhattan = sum(abs(x - y) for x, y in zip(a, b))
print(f"euclidean {euclidean:.4f}")
print(f"manhattan {manhattan:.4f}")