Skip to content

Instantly share code, notes, and snippets.

@maxmumford
Created August 14, 2014 09:40
Show Gist options
  • Save maxmumford/242969aa64a7b6462630 to your computer and use it in GitHub Desktop.
Save maxmumford/242969aa64a7b6462630 to your computer and use it in GitHub Desktop.
Random EAN13 Generator
#! /usr/bin/python
"""
This script generates a random EAN13 number and prints it to the standard out.
"""
from random import randrange
def generate_12_random_numbers():
numbers = []
for x in range(12):
numbers.append(randrange(10))
return numbers
def calculate_checksum(ean):
"""Calculates the checksum for EAN13-Code.
@param list ean: List of 12 numbers for first part of EAN13
:returns: The checksum for `ean`.
:rtype: Integer
"""
assert len(ean) == 12, "ean must be a list of 12 numbers for the first part of the EAN13"
sum_ = lambda x, y: int(x) + int(y)
evensum = reduce(sum_, ean[::2])
oddsum = reduce(sum_, ean[1::2])
return (10 - ((evensum + oddsum * 3) % 10)) % 10
numbers = generate_12_random_numbers()
numbers.append(calculate_checksum(numbers))
print ''.join(map(str, numbers))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment