he-021
1.000
Proposed solution
Looking at this problem, I need to implement a function that rescales a list of numbers so that the minimum becomes 0 and the maximum becomes 1, with all other numbers scaled linearly between them.
The linear transformation formula is:
`new_value = (old_value - min_value) / (max_value - min_value)`
Let me trace through the example:
- Input: [1.0, 2.0, 3.0, 4.0, 5.0]
- min_value = 1.0, max_value = 5.0
- For each number x: new_x = (x - 1.0) / (5.0 - 1.0) = (x - 1.0) / 4.0
- 1.0 โ (1.0-1.0)/4.0 = 0.0
- 2.0 โ (2.0-1.0)/4.0 = 0.25
- 3.0 โ (3.0-1.0)/4.0 = 0.5
- 4.0 โ (4.0-1.0)/4.0 = 0.75
- 5.0 โ (5.0-1.0)/4.0 = 1.0
This matches the expected output.
```python
from typing import List
def rescale_to_unit(numbers: List[float]) -> List[float]:
""" Given list of numbers (of at least two elements), apply a linear transform to that list,
such that the smallest number will become 0 and the largest will become 1
>>> rescale_to_unit([1.0, 2.0, 3.0, 4.0, 5.0])
[0.0, 0.25, 0.5, 0.75, 1.0]
"""
if not numbers:
return []
min_value = min(numbers)
max_value = max(numbers)
# Handle edge case where all numbers are the same
if min_value == max_value:
return [0.0] * len(numbers)
range_value = max_value - min_value
return [(x - min_value) / range_value for x in numbers]
```Test output (stdout)
. [100%] 1 passed in 0.01s
System prompt
You are an expert programmer. Solve the task exactly as specified. Output your solution as fenced code blocks using the required file name(s) and the exact function/type signatures requested. Prefer correctness; do not include prose outside code unless asked.