Created
February 28, 2019 18:08
-
-
Save magdiel01/cce595f3d228d22b87298021da44eb99 to your computer and use it in GitHub Desktop.
Python function which verifies UPCs check digit
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(value): | |
"""calculate UPCA and UPCE check digit""" | |
check_digit = 0 | |
odd_pos = True | |
for char in str(value)[::-1]: | |
if odd_pos: | |
check_digit += int(char) * 3 | |
else: | |
check_digit += int(char) | |
odd_pos = not odd_pos # alternate | |
check_digit = check_digit % 10 | |
check_digit = 10 - check_digit | |
check_digit = check_digit % 10 | |
return check_digit | |
def is_valid(upc): | |
return int(calc_check_digit(int(str(upc)[0:-1]))) == int(str(upc)[-1]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment