Skip to content

Instantly share code, notes, and snippets.

@derekstavis
Last active September 24, 2020 20:22
Show Gist options
  • Save derekstavis/ecfaf3e31a17d043f62c to your computer and use it in GitHub Desktop.
Save derekstavis/ecfaf3e31a17d043f62c to your computer and use it in GitHub Desktop.
Validação de CPF em Python
def validate_cpf(cpf):
''' Expects a numeric-only CPF string. '''
if len(cpf) < 11:
return False
if cpf in [s * 11 for s in [str(n) for n in range(10)]]:
return False
calc = lambda t: int(t[1]) * (t[0] + 2)
d1 = (sum(map(calc, enumerate(reversed(cpf[:-2])))) * 10) % 11
d2 = (sum(map(calc, enumerate(reversed(cpf[:-1])))) * 10) % 11
return str(d1) == cpf[-2] and str(d2) == cpf[-1]
'''
The MIT License (MIT)
Copyright (c) 2015 Derek Willian Stavis
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''
@clbcabral
Copy link

Aparentemente há um erro no script. O CPF válido 36041181404 está sendo tratado como inválido.

@Pandatree
Copy link

Como foi comentado:

    calc = lambda t: int(t[1]) * (t[0] + 2)
    d1 = (sum(map(calc, enumerate(reversed(cpf[:-2])))) * 10) % 11
    d2 = (sum(map(calc, enumerate(reversed(cpf[:-1])))) * 10) % 11
    return str(d1) == cpf[-2] and str(d2) == cpf[-1]

essa parte está retornando falsos negativos para alguns casos(especialmente quando o '%11' retorna '10' e quando o primeiro digito verificador é '0')
vou postar uma versão igualmente curta como sugestão:

    calc = [i for i in range(1, 10)]
    d1= (sum([int(a)*b for a,b in zip(num[:-2], calc)]) % 11) % 10
    d2= (sum([int(a)*b for a,b in zip(reversed(num[:-2]), calc)]) % 11) % 10
    return str(d1) == num[-2] and str(d2) == num[-1]

ele cria uma lista de 1 até 9,
multiplica essa lista com os digitos do cpf em ordem, tira o módulo e garante que se o número for 10, ele gera o 0
multiplica essa lista com os digitos do cpf invertidos, tira o módulo e garante que se o número for 10, ele gera o 0

basicamente a mesma coisa, com um metodo diferente, mas não entendi plenamente o que estava dando errado no teu.

@rafahlobo
Copy link

rafahlobo commented Mar 4, 2019

Quem tiver interesse pode olhar este repositório também. Funciona para CPF e CNPJ.
https://github.com/rafahlobo/cpfValidator

@marcaum54
Copy link

@rafahlobo essa https://github.com/rafahlobo/cpfValidator está aceitando caracteres repetidos: 11111111111 ...

@rafahlobo
Copy link

@rafahlobo essa https://github.com/rafahlobo/cpfValidator está aceitando caracteres repetidos: 11111111111 ...

Blz @marcaum54, vou testar aqui e corrijo. Obrigado pelo feedback.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment