#!/usr/bin/python # -*- coding: utf8 -*- NIP_WEIGHTS = [6,5, 7, 2, 3, 4, 5, 6,7] REGON9_WEIGHTS = [8, 9, 2, 3, 4, 5, 6, 7] REGON14_WEIGHTS = [2, 4, 8, 5, 0, 9, 7, 3, 6, 1, 2, 4, 8] class InvalidChecksumError(Exception): pass class InvalidInputError(Exception): pass def validate_nip(nip): nip = nip.replace('-', '') suma = 0 if nip.isdigit() and len(nip) == 10: for i in enumerate(nip[:-1]): suma += ( int(i[1]) * NIP_WEIGHTS[i[0]] ) div1 = divmod(suma, 11) div2 = divmod(div1[1], 10) if int(nip[-1]) == div2[1]: return nip raise InvalidChecksumError('Nieprawidłowa suma kontrolna') raise InvalidInputError('Nieprawidłowa forma NIP') def validate_regon(regon): regon = regon.replace('-', '') REGON_WEIGHTS = None if len(regon)== 9: REGON_WEIGHTS = REGON9_WEIGHTS elif len(regon) == 14: REGON_WEIGHTS = REGON14_WEIGHTS if REGON_WEIGHTS: suma = 0 for i in enumerate(regon[:-1]): suma += ( int(i[1]) * REGON_WEIGHTS[i[0]] ) div = divmod(suma, 11) if div[1] == int(regon[-1]): return regon raise InvalidChecksumError('Nieprawidłowa suma kontrolna') raise InvalidInputError('Nieprawidłowa forma REGON') if __name__ == '__main__': print validate_nip('123-456-32-18') print validate_regon('123456785') print validate_regon('12345678512347')