Problems › Python › validation
Verify a barcode
A scanner sometimes misreads a digit. The EAN-13 check digit catches most of those before the wrong product reaches the basket.
- The code is exactly thirteen digits.
- Counting from one, digits in odd positions count once and digits in even positions count three times.
- The code is valid when that total divides by ten.
- Anything not thirteen digits long, or containing a non-digit, is invalid.
barcode_valid(code: string) → bool
Where you start
def barcode_valid(code: str) -> bool:
Worked examples
| Call | Result |
|---|---|
barcode_valid("4006381333931") | True |
barcode_valid("4006381333932") | False |
barcode_valid("400638133393") | False |
barcode_valid("400638133393a") | False |
Hint
The check digit is the thirteenth and takes part in the sum like any other.
Reference solution in Python
def barcode_valid(code: str) -> bool:
if len(code) != 13 or not code.isdigit():
return False
total = 0
for i, c in enumerate(code):
d = int(c)
total += d if i % 2 == 0 else d * 3
return total % 10 == 0