Task: UPC




Go: package main

import (
    "fmt"
    "regexp"
)

var bits = []string{
    "0 0 0 1 1 0 1 ",
    "0 0 1 1 0 0 1 ",
    "0 0 1 0 0 1 1 ",
    "0 1 1 1 1 0 1 ",
    "0 1 0 0 0 1 1 ",
    "0 1 1 0 0 0 1 ",
    "0 1 0 1 1 1 1 ",
    "0 1 1 1 0 1 1 ",
    "0 1 1 0 1 1 1 ",
    "0 0 0 1 0 1 1 ",
}

var (
    lhs = make(map[string]int)
    rhs = make(map[string]int)
)

var weights = []int{3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1}

const (
    s = "# #"
    m = " # # "
    e = "# #"
    d = "(?:#| ){7}"
)

func init() {
    for i := 0; i <= 9; i++ {
        lt := make([]byte, 7)
        rt := make([]byte, 7)
        for j := 0; j < 14; j += 2 {
            if bits[i][j] == '1' {
                lt[j/2] = '#'
                rt[j/2] = ' '
            } else {
                lt[j/2] = ' '
                rt[j/2] = '#'
            }
        }
        lhs[string(lt)] = i
        rhs[string(rt)] = i
    }
}

func reverse(s string) string {
    b := []byte(s)
    for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
        b[i], b[j] = b[j], b[i]
    }
    return string(b)
}

func main() {
    barcodes := []string{
        "         # #   # ##  #  ## #   ## ### ## ### ## #### # # # ## ##  #   #  ##  ## ###  # ##  ## ### #  # #       ",
        "        # # #   ##   ## # #### #   # ## #   ## #   ## # # # ###  # ###  ##  ## ###  # #  ### ###  # # #         ",
        "         # #    # # #  ###  #   #    # #  #   #    # # # # ## #   ## #   ## #   ##   # # #### ### ## # #         ",
        "       # # ##  ## ##  ##   #  #   #  # ###  # ##  ## # # #   ## ##  #  ### ## ## #   # #### ## #   # #        ",
        "         # # ### ## #   ## ## ###  ##  # ##   #   # ## # # ### #  ## ##  #    # ### #  ## ##  #      # #          ",
        "          # #  #   # ##  ##  #   #   #  # ##  ##  #   # # # # #### #  ##  # #### #### # #  ##  # #### # #         ",
        "         # #  #  ##  ##  # #   ## ##   # ### ## ##   # # # #  #   #   #  #  ### # #    ###  # #  #   # #        ",
        "        # # #    # ##  ##   #  # ##  ##  ### #   #  # # # ### ## ## ### ## ### ### ## #  ##  ### ## # #         ",
        "         # # ### ##   ## # # #### #   ## # #### # #### # # #   #  # ###  #    # ###  # #    # ###  # # #       ",
        "        # # # #### ##   # #### # #   ## ## ### #### # # # #  ### # ###  ###  # # ###  #    # #  ### # #         ",
    }

    
    
    expr := fmt.Sprintf(`^\s*%s(%s)(%s)(%s)(%s)(%s)(%s)%s(%s)(%s)(%s)(%s)(%s)(%s)%s\s*$`,
        s, d, d, d, d, d, d, m, d, d, d, d, d, d, e)
    rx := regexp.MustCompile(expr)
    fmt.Println("UPC-A barcodes:")
    for i, bc := range barcodes {
        for j := 0; j <= 1; j++ {
            if !rx.MatchString(bc) {
                fmt.Printf("%2d: Invalid format\n", i+1)
                break
            }
            codes := rx.FindStringSubmatch(bc)
            digits := make([]int, 12)
            var invalid, ok bool 
            for i := 1; i <= 6; i++ {
                digits[i-1], ok = lhs[codes[i]]
                if !ok {
                    invalid = true
                }
                digits[i+5], ok = rhs[codes[i+6]]
                if !ok {
                    invalid = true
                }
            }
            if invalid { 
                if j == 0 { 
                    bc = reverse(bc)
                    continue
                } else {
                    fmt.Printf("%2d: Invalid digit(s)\n", i+1)
                    break
                }
            }
            sum := 0
            for i, d := range digits {
                sum += weights[i] * d
            }
            if sum%10 != 0 {
                fmt.Printf("%2d: Checksum error\n", i+1)
                break
            } else {
                ud := ""
                if j == 1 {
                    ud = "(upside down)"
                }
                fmt.Printf("%2d: %v %s\n", i+1, digits, ud)
                break
            }
        }
    }
}




Python: 
import itertools
import re

RE_BARCODE = re.compile(
    r"^(?P<s_quiet> +)"  
    r"(?P<s_guard>
    r"(?P<left>[ 
    r"(?P<m_guard> 
    r"(?P<right>[ 
    r"(?P<e_guard>
    r"(?P<e_quiet> +)$"  
)

LEFT_DIGITS = {
    (0, 0, 0, 1, 1, 0, 1): 0,
    (0, 0, 1, 1, 0, 0, 1): 1,
    (0, 0, 1, 0, 0, 1, 1): 2,
    (0, 1, 1, 1, 1, 0, 1): 3,
    (0, 1, 0, 0, 0, 1, 1): 4,
    (0, 1, 1, 0, 0, 0, 1): 5,
    (0, 1, 0, 1, 1, 1, 1): 6,
    (0, 1, 1, 1, 0, 1, 1): 7,
    (0, 1, 1, 0, 1, 1, 1): 8,
    (0, 0, 0, 1, 0, 1, 1): 9,
}

RIGHT_DIGITS = {
    (1, 1, 1, 0, 0, 1, 0): 0,
    (1, 1, 0, 0, 1, 1, 0): 1,
    (1, 1, 0, 1, 1, 0, 0): 2,
    (1, 0, 0, 0, 0, 1, 0): 3,
    (1, 0, 1, 1, 1, 0, 0): 4,
    (1, 0, 0, 1, 1, 1, 0): 5,
    (1, 0, 1, 0, 0, 0, 0): 6,
    (1, 0, 0, 0, 1, 0, 0): 7,
    (1, 0, 0, 1, 0, 0, 0): 8,
    (1, 1, 1, 0, 1, 0, 0): 9,
}


MODULES = {
    " ": 0,
    "
}

DIGITS_PER_SIDE = 6
MODULES_PER_DIGIT = 7


class ParityError(Exception):
    


class ChecksumError(Exception):
    


def group(iterable, n):
    
    args = [iter(iterable)] * n
    return tuple(itertools.zip_longest(*args))


def parse(barcode):
    
    match = RE_BARCODE.match(barcode)

    
    
    left = group((MODULES[c] for c in match.group("left")), MODULES_PER_DIGIT)
    right = group((MODULES[c] for c in match.group("right")), MODULES_PER_DIGIT)

    
    left, right = check_parity(left, right)

    
    return tuple(
        itertools.chain(
            (LEFT_DIGITS[d] for d in left),
            (RIGHT_DIGITS[d] for d in right),
        )
    )


def check_parity(left, right):
    
    
    
    
    left_parity = sum(sum(d) % 2 for d in left)
    right_parity = sum(sum(d) % 2 for d in right)

    
    
    if left_parity == 0 and right_parity == DIGITS_PER_SIDE:
        _left = tuple(tuple(reversed(d)) for d in reversed(right))
        right = tuple(tuple(reversed(d)) for d in reversed(left))
        left = _left
    elif left_parity != DIGITS_PER_SIDE or right_parity != 0:
        
        error = tuple(
            itertools.chain(
                (LEFT_DIGITS.get(d, "_") for d in left),
                (RIGHT_DIGITS.get(d, "_") for d in right),
            )
        )
        raise ParityError(" ".join(str(d) for d in error))

    return left, right


def checksum(digits):
    
    odds = (digits[i] for i in range(0, 11, 2))
    evens = (digits[i] for i in range(1, 10, 2))

    check_digit = (sum(odds) * 3 + sum(evens)) % 10

    if check_digit != 0:
        check_digit = 10 - check_digit

    if digits[-1] != check_digit:
        raise ChecksumError(str(check_digit))

    return check_digit


def main():
    barcodes = [
        "         
        "        
        "         
        "       
        "         
        "          
        "         
        "        
        "         
        "        
        "        
    ]

    for barcode in barcodes:
        try:
            digits = parse(barcode)
        except ParityError as err:
            print(f"{err} parity error!")
            continue

        try:
            check_digit = checksum(digits)
        except ChecksumError as err:
            print(f"{' '.join(str(d) for d in digits)} checksum error! ({err})")
            continue

        print(f"{' '.join(str(d) for d in digits)}")


if __name__ == "__main__":
    main()