Last active
August 21, 2020 01:36
-
-
Save henriquebastos/9040667 to your computer and use it in GitHub Desktop.
Brincando com recursos do Python para calcular se um cpf é válido
This file contains hidden or 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
# coding: utf-8 | |
def cpf_checksum(value): | |
""" | |
CPF Checksum algorithm. | |
""" | |
def dv(partial): | |
s = sum(b * int(v) for b, v in zip(range(len(partial)+1, 1, -1), partial)) | |
return s % 11 | |
dv1 = 11 - dv(value[:9]) | |
q2 = dv(value[:10]) | |
dv2 = 11 - q2 if q2 >= 2 else 0 | |
return dv1 == int(value[9]) and dv2 == int(value[10]) | |
def tests(): | |
assert cpf_checksum('11144477735') == True | |
assert cpf_checksum('21111111120') == True | |
assert cpf_checksum('00000000000') == False | |
tests() |
linha 16 está sobrando um ':' no final
e nas linhas 12, 13 e 16 troquei value por cpf
Outra implementação mais procedural da função dv:
def dv(partial):
s = 0
base = len(partial)+1
# percorre 10 ou 11 (dependendo do tamanho do partial) até 2
for b in range(base, 1, -1):
c = base - b # para percorrermos o partial de 0 até 9 ou 10, dependendo do tamanho do partial
s += b * int(partial[c])
return s % 11
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Baseado na explicação do blog Interformação.