I altered the check to the first 2 characters to explicitly test that they were A-Z alpha characters. (The original only checked that they were non-numeric)
I also removed the message regarding the preference for upper-case letters. Since the function converts to upper anyway, it seemed unnecessary to bother the tester with that.
I did not bother to test my suspicion, but I was concerned that the function would throw a traceback error if the tester had entered a non-alpha at the beginning of the ID and it was subsequently submitted to the .upper() method later in the function.
In general, I was delighted with the elegance of this solution to validating input from the tester.
Pete's changes:
def validate_id(some_id):
# Basic checks: len == 7, first two chars letters,
# all other chars are numbers
if len(some_id) != 7:
return False
if not some_id[0].isalpha():
return False
if not some_id[1].isalpha():
return False
if not all([n.isdecimal() for n in some_id[2:6]]):
return False
# Convert ID to array of numbers, excluding check digit
id_array = []
id_array.append(ord(some_id[0].upper()))
id_array.append(ord(some_id[1].upper()))
id_array = id_array + list(some_id[2:6])
# Use check digit algorithm to generate correct check digit
check_digit_array = []
for pos in range(len(id_array)):
check_digit_array.append(int(id_array[pos]) * (pos+1))
check_digit = sum(check_digit_array) % 10
# Check correct check digit against entered ID
if int(some_id[6]) != check_digit:
return False
return True
Pete's comments:
I made 2 minor changes to the original:
I altered the check to the first 2 characters to explicitly test that they were A-Z alpha characters. (The original only checked that they were non-numeric)
I also removed the message regarding the preference for upper-case letters. Since the function converts to upper anyway, it seemed unnecessary to bother the tester with that.
I did not bother to test my suspicion, but I was concerned that the function would throw a traceback error if the tester had entered a non-alpha at the beginning of the ID and it was subsequently submitted to the
.upper()
method later in the function.In general, I was delighted with the elegance of this solution to validating input from the tester.
Pete's changes:
cc @sbouix