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)