Last active
October 30, 2019 14:21
-
-
Save lucascnr/8ec9d037db901260f81b0d150ece38c4 to your computer and use it in GitHub Desktop.
This script generates a random EAN13 number and prints it to the standard out.
This file contains hidden or 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
#! /usr/bin/python | |
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 | |
x = int(raw_input('How many?')) | |
for _ in range(x): | |
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