Write the function at the heart of every chart: map data values to positions.
What to build
A program that maps values through a linear scale, clamping values outside the domain.
Requirements
- Map each value from the domain d0..d1 to the range r0..r1; a value outside the domain is first moved to the nearest end of the domain.
- Print
V -> Pper value, V written with Python's:gformat and P with one decimal place.
Input
Line 1: d0 d1. Line 2: r0 r1. Line 3: the values separated by spaces.
Output
One line per value.
Constraints
d0 < d1; 1 to 100 values.
Example
Input:
0 100
0 400
0 25 50 100
Output:
0 -> 0.0
25 -> 100.0
50 -> 200.0
100 -> 400.0
Why it works
The fraction along the domain becomes the same fraction along the range, which also works when the range is flipped for screen coordinates; clamping keeps stray values inside the chart.
Examples
Example 1 · Input
0 100 0 400 0 25 50 100
Expected output
0 -> 0.0 25 -> 100.0 50 -> 200.0 100 -> 400.0
Example 2 · Input
0 100 300 0 0 50 120
Expected output
0 -> 300.0 50 -> 150.0 120 -> 0.0
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
The position is r0 + (v - d0) / (d1 - d0) * (r1 - r0).
Hint 2
Clamp v into the domain with min and max before mapping.
Solution
Show one correct solution (try it yourself first)
d0, d1 = map(float, input().split())
r0, r1 = map(float, input().split())
for v in map(float, input().split()):
c = min(max(v, d0), d1)
p = r0 + (c - d0) / (d1 - d0) * (r1 - r0)
print(f"{v:g} -> {p:.1f}")