Composing Small Functions
~10 mincode completion
Write two functions. The tests call both, so both have to work.
normalise(value, low, high)returns wherevaluesits betweenlowandhigh, as a number from 0 to 1. The formula is(value - low) / (high - low). Withlow=0, high=10, the value 2.5 gives0.25.
normalise_all(values, low, high)returns a list with every value normalised, by callingnormaliserather than repeating the formula.
You will use exactly this operation in the ML sections under the name min-max scaling.
Examples
- Input
- normalise(2.5, 0, 10)
- Output
- 0.25
The low end of the range maps to 0
- Input
- normalise(5, 5, 15)
- Output
- 0
The high end of the range maps to 1
- Input
- normalise(15, 5, 15)
- Output
- 1
Hints
Hint 1
A list comprehension expresses this in one line.
Hint 2
A common slip here: duplicated formula instead of calling.
Requirements
value: the number to scalelow: the value that maps to 0high: the value that maps to 1Return (value - low) / (high - low)
Constraints
Standard library only, no imports required
Time limit: 200 ms, Memory: 64 MB
Where this shows up
~10 min
••••••
3 employers weight this skill
2 frontier labs, 1 AI product company. Top match scores 80.
Python
def normalise(value, low, high):
"""
Map a value onto a 0 to 1 scale.
Args:
value: the number to scale
low: the value that maps to 0
high: the value that maps to 1
Returns:
(value - low) / (high - low)
"""
# YOUR CODE HERE
pass
def normalise_all(values, low, high):
"""
Normalise a whole list by calling normalise on each item.
Args:
values: a list of numbers
low, high: the range, as above
Returns:
A list of normalised values.
"""
# YOUR CODE HERE
pass