Skip to content

Instantly share code, notes, and snippets.

@leorochael
Last active May 14, 2020 04:29
Show Gist options
  • Save leorochael/e0362d61fed1223585546cdf9beaf05c to your computer and use it in GitHub Desktop.
Save leorochael/e0362d61fed1223585546cdf9beaf05c to your computer and use it in GitHub Desktop.
# Based on the description found at https://dicasdeprogramacao.com.br/algoritmo-para-validar-cpf/
def get_cpf_mod_11_digit(digits):
weights = range(len(digits) + 1, 1, -1)
weighted = [digit * weight for digit, weight in zip(digits, weights)]
weighted_sum = sum(weighted)
extra_digit = weighted_sum * 10 % 11 % 10
return extra_digit
def int_to_cpf_with_digits(num):
assert num < 1000000000
digits = [int(digit) for digit in f'{num:09d}']
digit1 = get_cpf_mod_11_digit(digits)
digits.append(digit1)
digit2 = get_cpf_mod_11_digit(digits)
digits.append(digit2)
digits_str = "".join(str(digit) for digit in digits)
return digits_str
def add_cpf_mask(digits_str):
return f'{digits_str[:3]}.{digits_str[3:6]}.{digits_str[6:9]}-{digits_str[9:]}'
print(add_cpf_mask(int_to_cpf_with_digits(529982247)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment