Last active
November 2, 2021 22:32
-
-
Save davincif/0f200175c1e02b2ed8a126c1d0c0d3f0 to your computer and use it in GitHub Desktop.
CPF Validation
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
import re | |
nondigit = re.compile('\D'); | |
def validate_cpf(cpf): | |
global nondigit | |
cpf = nondigit.sub('', cpf) | |
if len(cpf) < 11: | |
raise Exception("CPF inválido") | |
vcode = [] # verification digit | |
for count in range(2): | |
count += 1 | |
aux = [num for num in range(2, 10 + count)] | |
aux.reverse() | |
cpflist = [int(digit) for digit in cpf] | |
digit = 11 - sum(map(lambda tp: tp[0] * tp[1], zip(cpflist, aux))) % 11 | |
digit = digit if digit <= 9 else 0 | |
vcode.append(str(digit)) | |
vcode = ''.join(vcode) | |
if vcode != cpf[-2:]: | |
raise Exception("CPF inválido") | |
return True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment