P4.2.1Resistor colour codes
The values and tolerances of older resistors are identified by four coloured bands: the first two indicate the first two significant figures of the resistance in ohms, the third denotes a decimal multiplier (number of zeros), and the fourth indicates the tolerance. The colours and their meanings for each band are listed in the table below.
For example, a resistor with coloured bands: violet, yellow, red, green has value \(74 \times 10^2 = 7400\;\mathrm{\Omega}\) and tolerance \(\pm 0.5\%\).
Write a program which defines a function to translate a list of four colour abbreviations into a resistance value and a tolerance. For example:
>>> print(get_resistor_value(['vi', 'yl', 'rd', 'gr']))
(7400, 0.5)
| Colour | Abbreviation | Significant figures | Multiplier | Tolerance |
|---|---|---|---|---|
| Black | bk | 0 | 1 | -- |
| Brown | br | 1 | 10 | \(\pm 1\%\) |
| Red | rd | 2 | \(10^2\) | \(\pm 2\%\) |
| Orange | or | 3 | \(10^3\) | -- |
| Yellow | yl | 4 | \(10^4\) | \(\pm 5\%\) |
| Green | gr | 5 | \(10^5\) | \(\pm 0.5\%\) |
| Blue | bl | 6 | \(10^6\) | \(\pm 0.25\%\) |
| Violet | vi | 7 | \(10^7\) | \(\pm 0.1\%\) |
| Grey | gy | 8 | \(10^8\) | \(\pm 0.05\%\) |
| White | wh | 9 | \(10^9\) | -- |
| Gold | au | -- | -- | \(\pm 5\%\) |
| Silver | ag | -- | -- | \(\pm 10\%\) |
| None | -- | -- | -- | \(\pm 20\%\) |
Show solution
The dictionaries nums and tol map the color abbreviations to the digits \(0-9\) and tolerances.
# List of band colour abbreviations
colours = ['bk','br','rd','or','yl','gr','bl','vi','gy','wh','au','ag','--']
# Dictionary mapping colour abbreviations to numbers:
# e.g. 'bk': 0, 'br': 1, ..., 'wh': 9
nums = {}
for i, col in enumerate(colours[:10]):
nums[col] = i
# Tolerances by colour abbreviation (in %)
tol = {'br': 1, 'rd': 2, 'gr': 0.5, 'bl': 0.25, 'vi': 0.1, 'gy': 0.05,
'au': 5, 'ag': 10, '--': 20}
def get_resistor_value(bands):
"""
Return the resistance in ohms and its uncertainty corresponding to
a given sequence of four band colours.
"""
# first two bands are significant figures, third is number of zeros
try:
val = (nums[bands[0]]*10 + nums[bands[1]])\
* pow(10, nums[bands[2]])
tolerance = tol[bands[3]]
except KeyError:
print('Unidentified or invalid band colour in bands:', bands)
return None, None
except IndexError:
print('Fewer than four colours provided in bands:', bands)
return None, None
return val, tolerance
print(get_resistor_value(['br', 'bk', 'yl', 'ag']))
print(get_resistor_value(['yl', 'vi', 'rd', 'au']))
print(get_resistor_value(['vi', 'yl', 'rd', 'gr']))
print(get_resistor_value(['ws', 'yl', 'rd', 'rd']))
print(get_resistor_value(['vi', 'yl', 'rd']))
Output:
(100000, 10)
(4700, 5)
(7400, 0.5)
Unidentified or invalid band colour in bands: ['ws', 'yl', 'rd', 'rd']
(None, None)
Fewer than four colours provided in bands: ['vi', 'yl', 'rd']
(None, None)