Skip to content

Instantly share code, notes, and snippets.

Created July 11, 2012 03:09
Show Gist options
  • Select an option

  • Save anonymous/3087725 to your computer and use it in GitHub Desktop.

Select an option

Save anonymous/3087725 to your computer and use it in GitHub Desktop.
from itertools import cycle
def mod11(key, peso):
numeros = reversed(map(int, key))
soma = sum(n * m for n, m in zip(numeros, cycle(range(2,(peso+1)))))
resto = soma % 11
if resto < 2:
return 0
else:
return 11 - resto
def nfe_dv(key):
return str(mod11(key,9))
def cnpj_dv(key):
d1 = str(mod11(key,9))
d2 = str(mod11(key + d1,9))
return d1+d2
def cpf_dv(key):
d1 = str(mod11(key,10))
d2 = str(mod11(key + d1,11))
return d1+d2
def ie_dv(estado, key):
if estado.upper() in ('GO', 'AL', 'CE'):
assert len(key) == 8
return str(mod11(key,9))
if estado.upper() == 'AC':
assert len(key) == 11
d1 = str(mod11(key,9))
d2 = str(mod11(key + d1,9))
return d1+d2
teste_nfe = '31090807301671000131550010001000200905000585'
assert nfe_dv(teste_nfe[:-1]) == teste_nfe[-1]
teste_cnpj = '10382300000136'
assert cnpj_dv(teste_cnpj[:-2]) == teste_cnpj[-2:]
teste_cpf = '69195196153'
assert cpf_dv(teste_cpf[:-2]) == teste_cpf[-2:]
teste_ie_go = '109876547'
assert ie_dv('GO','10987654') == '7'
teste_ie_ac = '0100482300112'
assert ie_dv('AC','01004823001') == '12'
teste_ie_al = '240000048'
assert ie_dv('AL','24000004') == '8'
teste_ie_ce = '060000015'
assert ie_dv('CE','06000001') == '5'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment