Created
December 28, 2013 21:11
-
-
Save carrerasrodrigo/8164258 to your computer and use it in GitHub Desktop.
This snippet includes two method that helps you working with CPF (brazilian documents).
This file contains 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 random | |
def generate_cpf(): | |
"""Generates a random, valid CPF (brazilian document) | |
Reference: http://www.geradorcpf.com/algoritmo_do_cpf.htm | |
""" | |
cpf = [random.randint(1, 9) for i in range(9)] | |
weight = range(10, 1, -1) | |
weight2 = range(11, 1, -1) | |
tmp = [0, 0, 0, 0, 0, 0, 0, 0, 0] | |
# first verificator digit | |
for i in range(9): | |
tmp[i] = cpf[i] * weight[i] | |
rest = sum(tmp) % 11 | |
v1 = 11 - rest if rest >= 2 else 0 | |
cpf.append(v1) | |
tmp.append(0) | |
# second verificator digit | |
for i in range(10): | |
tmp[i] = cpf[i] * weight2[i] | |
rest = sum(tmp) % 11 | |
v2 = 11 - rest if rest >= 2 else 0 | |
cpf.append(v2) | |
# Return the cpf | |
cpf = [str(i) for i in cpf] | |
return "{0}.{1}.{2}-{3}".format("".join(cpf[0:3]), | |
"".join(cpf[3:6]), | |
"".join(cpf[6:9]), | |
"".join(cpf[9:11])) | |
def validate_cpf(cpf): | |
"""Validates a CPF (brazilian document) | |
Returns True is the CPF is valid, False otherwise | |
Reference: http://www.geradorcpf.com/script-validar-cpf-php.htm | |
""" | |
cpf = cpf.replace(".", "").replace("-", "") | |
if len(cpf) != 11: | |
return False | |
tt = 0 | |
for t in range(9, 11): | |
d = 0 | |
for c in range(0, t): | |
d += int(cpf[c]) * ((t + 1) - c) | |
tt += 1 | |
d = ((10 * d) % 11) % 10 | |
if int(cpf[c+1]) != d: | |
return False | |
return True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment