2025-01-23
Max. 100 points
Name:
Task | Max. | Achieved |
---|---|---|
1 | 50 | |
2 | 50 | |
Sum | 100 |
generate_colors(resistance: int) -> list[str]
that takes a desired resistance value and returns a list of colors to
be printed. For example:
>>> generate_colors(330)
['orange', 'orange', 'brown']
>>> generate_colors(8200)
['grey', 'red', 'red']
Use function annotations and a docstring including a doctest to receive
full points.
values = [ # value corresponds to index of color
"black", "brown", "red", "orange", "yellow", "green", "blue", "violet",
"grey", "white"]
def generate_colors(resistance: int) -> list[str]:
"""
Generate the colors on a resistor given its resistance.
>>> generate_colors(330)
['orange', 'orange', 'brown']
"""
colors = []
resistance = str(resistance)
colors.append(values[int(resistance[0])])
colors.append(values[int(resistance[1])])
colors.append(values[len(resistance[2:])])
return colors
generate_colors(.)
above solves the
manufacturer's problem of printing the correct colors. Now, it is your
duty to solve the hobbyist's problem of de-coding the colors into a
human readable resistance value. Implement a function
decode_resistance(colors: list[str]) -> str
that takes a list of colors and returns the decoded resistance. Note that
the resulting resistance has to be represented as a string including
the proper unit using a metric prefix whenever appropriate. For example:
>>> decode_resistance(['orange', 'orange', 'brown'])
'330 ohms'
>>> decode_resistance(['grey', 'red', 'red'])
'8.2 kiloohms'
>>> decode_resistance(['grey', 'red', 'blue'])
'82.0 megaohms'
Use function annotations and a docstring including a doctest to receive
full points.
values = [ # value corresponds to index of color
"black", "brown", "red", "orange", "yellow", "green", "blue", "violet",
"grey", "white"]
def decode_resistance(colors: list[str]) -> str:
"""
Return a resistance value in ohms given its color bands.
>>> decode_resistance(['grey', 'red', 'red'])
'8.2 kiloohms'
"""
base_value = values.index(colors[0]) * 10 + values.index(colors[1])
value = base_value * 10 ** values.index(colors[2])
unit = "ohms"
if value // 10 ** 9:
unit = "gigaohms"
value /= 10 ** 9
elif value // 10 ** 6:
unit = "megaohms"
value /= 10 ** 6
elif value // 10 ** 3:
unit = "kiloohms"
value /= 10 ** 3
return f'{value} {unit}'