Last active
April 2, 2023 17:46
-
-
Save xv/296d2cdedac88d54cdcd4dc643dfedcb to your computer and use it in GitHub Desktop.
Python function to calculate the check digit of a UPC-12 barcode.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def calc_check_digit(digits): | |
digits = [int(i) for i in str(digits)][:-1] | |
odd_pos_list = digits[0::2] # 1st, 3rd, 5th, etc | |
even_pos_list = digits[1::2] # 2nd, 4th, 6th, etc | |
n = (sum(odd_pos_list) * 3) + sum(even_pos_list) | |
rmndr = n % 10 | |
return (10 - rmndr) if rmndr > 0 else 0 | |
# Full 12 digits of a UPC-12 barcode | |
digits = '123601057072' | |
check_digit = calc_check_digit(digits) | |
# Return value should match the 12th digit on the barcode | |
print(check_digit) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment