Search code examples
pythonpython-2.7computer-science

Python EAN-13 Barcode generator script overflow


I have a script that generates all possible EAN-13 barcodes. Problem is that it doesn't run because I believe I'm getting arithmetic overflows. Is it possible to optimize this so I can get all the possible values? A EAN-13 barcode looks like 0000000000001,1000000000000 or 0293401925347, etc. Total combinations should be 10^13:

for k in range(13, 14):
    for number in list(product(range(13), repeat=k)):
        barcode = "".join(map(str, number))
        print(barcode)

Solution

  • There are some problems with your code. Let's look at the differences to

    from itertools import product
    
    k = 13
    
    for number in product(range(10), repeat = k):
        barcode = "".join(map(str, number))
        print(barcode)
    

    1) Your loop for k is in the range(13, 14). This is the same as k=13
    2) Your range(13) is wrong, since we only want to join digits 0 to 9
    3) You wrote list(product(). This creates a list of 10^13 numbers, which takes a lot of space and time to produce. Iterate instead over the itertools object directly to avoid this. If you want to know more about iterators and generators, please have a look at this introduction to generators. Tldr: Advantage: they produce the next element only, when asked, saving memory space and computing time for elements, we don't use. Disadvantage: They exhaust, i.e. once a generated element has been used, the generator can't access it any more.