Have a go at it. The editor and the docs panel are open, and your code is saved as you type. Running it needs a free account — you’ll come back to exactly what you wrote.
Composing Small Functions
Functions get their real value when you build them out of each other. A long function that does four things is harder to test, harder to fix, and harder to reuse than four short ones.
def celsius_to_fahrenheit(c):
return c * 9 / 5 + 32
def describe(c):
f = celsius_to_fahrenheit(c)
return f"{c}C is {f}F"describe does not repeat the conversion formula. If the formula is ever wrong, there is exactly one place to fix it.
Your task:
Write two functions. The tests call both, so both have to work.
normalise(value, low, high) returns where value sits between low and high, as a number from 0 to 1. The formula is (value - low) / (high - low). With low=0, high=10, the value 2.5 gives 0.25.normalise_all(values, low, high) returns a list with every value normalised, by calling normalise rather than repeating the formula.You will use exactly this operation in the ML sections under the name min-max scaling.
Example Tests
normalise puts 2.5 a quarter of the way along 0 to 10
Input: {"low":0,"high":10,"value":2.5}
Expected: 0.25
The low end of the range maps to 0
Input: {"low":5,"high":15,"value":5}
Expected: 0
The high end of the range maps to 1
Input: {"low":5,"high":15,"value":15}
Expected: 1
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
passRun your code to see results
⌘↵ runs against the visible tests