Validating GRids: A Python GRid check digit calculator
June 27, 2012
A Global Resource Identifier, or GRid, is used in the music industry to uniquely identify digital data such as sound recordings. Like barcodes, the last digit is a check digit to verify that the preceding digits were correct.
Calculating the check digit for a GRid is a little more of an obscure need than barcodes, but this Python code snippet will save whomever needs to do it in Python a bunch of time!
def calculate_grid_check_digit(grid):
"""
Assumes `grid` is 17 characters long
and missing the check digit.
"""
def _mod_36(i):
"""
A modified modulus function is used
by the algorithm.
"""
m = i % 36
return 36 if m == 0 else m
grid = grid.upper()
lookup_values = ['0','1','2','3','4','5','6','7','8','9',
'A','B','C','D','E','F','G','H','I','J',
'K','L','M','N','O','P','Q','R','S','T',
'U','V','W','X','Y','Z']
p_list = [36]
s_list = []
for j, c in enumerate(grid):
c_val = lookup_values.index(c)
s_list.append(p_list[j]%37+int(c_val))
p_list.append(_mod_36(s_list[j]) * 2)
i = 0
while 1:
if _mod_36(p_list[-1]%37 + i) == 1:
break;
i += 1
return lookup_values[i]
You can read more on GRids at the International Federation of the Phonographic Industry website and access their online GRid validator. (Don't view the JavaScript source though, for the code is terrible!)
Categories: Programming, Python
blog comments powered by Disqus