Skip to content

Instantly share code, notes, and snippets.

@vstoykov
Created August 10, 2011 15:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vstoykov/1137057 to your computer and use it in GitHub Desktop.
Save vstoykov/1137057 to your computer and use it in GitHub Desktop.
Method for checking validity of bulgarian EGN codes.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# egn_checker.py
#
# Copyright 2011 Venelin Stoykov <venelin@magicbg.com>
#
# 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)
@skanev
Copy link

skanev commented Aug 11, 2011

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 do sum % 11 % 10.

@vstoykov
Copy link
Author

10x

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment