Created
August 10, 2011 15:08
-
-
Save vstoykov/1137057 to your computer and use it in GitHub Desktop.
Method for checking validity of bulgarian EGN codes.
This file contains 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/env python | |
# -*- coding: utf-8 -*- | |
# | |
# egn_checker.py | |
# | |
# Copyright 2011 Venelin Stoykov <[email protected]> | |
# | |
# This program is free software; you can redistribute it and/or modify | |
# it under the terms of the GNU General Public License as published by | |
# the Free Software Foundation; either version 2 of the License, or | |
# (at your option) any later version. | |
# | |
# This program is distributed in the hope that it will be useful, | |
# but WITHOUT ANY WARRANTY; without even the implied warranty of | |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
# GNU General Public License for more details. | |
# | |
# You should have received a copy of the GNU General Public License | |
# along with this program; if not, write to the Free Software | |
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, | |
# MA 02110-1301, USA. | |
def egn_checker(egn): | |
''' | |
Check Bulgarian EGN codes for validity | |
full information about algoritm is available here | |
http://www.grao.bg/esgraon.html#section2 | |
''' | |
def check_validation_code(egn): | |
_weights = (2, 4, 8, 5, 10, 9, 7, 3, 6) | |
try: | |
my_sum = sum([weight * int(digit) for weight, digit in zip(_weights, egn)]) | |
return int(egn[-1]) == my_sum % 11 % 10 | |
except ValueError: | |
return False | |
def check_valid_date(egn): | |
from datetime import datetime | |
try: | |
year, month, day = int(egn[0:2]), int(egn[2:4]), int(egn[4:6]) | |
except: | |
return False | |
if month >= 40: | |
month -= 40 | |
year += 2000 | |
elif month >= 20: | |
month -= 20 | |
year += 1800 | |
else: | |
year += 1900 | |
try: | |
datetime.strptime('%s-%s-%s' % (year, month, day), "%Y-%m-%d") | |
return True | |
except ValueError: | |
return False | |
return len(egn) == 10 and check_validation_code(egn) and check_valid_date(egn) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Row 32 can be:
sum(weight * int(digit) for weight, digit in zip(weights, egn))
Also, instead of
str(my_sum % 11)[-1]
, you can dosum % 11 % 10
.