Skip to content

Instantly share code, notes, and snippets.

@davincif
Last active November 2, 2021 22:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davincif/0f200175c1e02b2ed8a126c1d0c0d3f0 to your computer and use it in GitHub Desktop.
Save davincif/0f200175c1e02b2ed8a126c1d0c0d3f0 to your computer and use it in GitHub Desktop.
CPF Validation
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