Sure! Here's a Python function that calculates the checksum for a given array of digits representing an EAN barcode:
def calculate_ean_checksum(digits):
"""Calculates the EAN checksum for a given array of digits.
Args:
digits (list): A list of integers representing the EAN barcode digits.
The length of the list must be either 12 or 13.
Returns:
int: The calculated checksum digit.
"""
if len(digits) not in (12, 13):
raise ValueError("Invalid number of digits. Expected 12 or 13, got {}.".format(len(digits)))
# Multiply every other digit by 3, starting with the first digit
odd_digits = [digit * 3 for i, digit in enumerate(digits) if i % 2 == 0]
even_digits = [digit for i, digit in enumerate(digits) if i % 2 != 0]
# Sum up the digits
total_sum = sum(odd_digits) + sum(even_digits)
# Calculate the checksum digit
checksum = (10 - (total_sum % 10)) % 10
return checksum
You can use this function by passing an array of integers representing the EAN barcode digits, like this:
digits = [7, 8, 9, 5, 0, 1, 2, 3, 4, 5, 6]
checksum = calculate_ean_checksum(digits)
print("Checksum digit:", checksum)
The checksum digit is the last digit of a valid EAN barcode. If you want to check a complete EAN barcode, including the checksum digit, you can call this function with the first 12 digits and then compare the calculated checksum digit with the given one. If they match, the barcode is valid.
Here's a complete example demonstrating how to check a complete EAN barcode:
def is_ean_valid(barcode):
"""Checks if a given EAN barcode is valid.
Args:
barcode (str): A string representing the EAN barcode, including the checksum digit.
Returns:
bool: True if the barcode is valid, False otherwise.
"""
digits = [int(digit) for digit in barcode]
if len(digits) != 13:
raise ValueError("Invalid EAN barcode. Expected 13 digits, got {}.".format(len(digits)))
calculated_checksum = calculate_ean_checksum(digits[:-1])
return calculated_checksum == digits[-1]
barcode = "789501234567"
if is_ean_valid(barcode):
print("Barcode is valid.")
else:
print("Barcode is invalid.")
This example defines an is_ean_valid function that checks if a given EAN barcode is valid. It first extracts the digits from the barcode string, calculates the checksum digit for the first 12 digits, and then compares the calculated checksum digit with the given one. If they match, the barcode is valid, and the function returns True.