Skip to content

Instantly share code, notes, and snippets.

@JPaulMora
Last active March 10, 2023 16:17
Show Gist options
  • Save JPaulMora/8e573abc67c871d5d174f6bab71c1f56 to your computer and use it in GitHub Desktop.
Save JPaulMora/8e573abc67c871d5d174f6bab71c1f56 to your computer and use it in GitHub Desktop.
Validar NIT en Python
import re
def nit_is_valid(nit):
if not nit:
return True
nit_regex = re.compile(r'^\d+(-?\d|k|K)?$')
if not nit_regex.match(nit):
return False
nit = nit.replace('-', '')
number = nit[:-1]
expected_checker = nit[-1].lower()
total = sum((int(digit) * factor) for factor, digit in enumerate(number[::-1], start=2))
modulus = (11 - (total % 11)) % 11
computed_checker = 'k' if modulus == 10 else str(modulus)
return expected_checker == computed_checker
@JPaulMora
Copy link
Author

For readability, you may change total with this version:

    factors = list(range(len(digits) + 1, 1, -1))
    products = [int(digit) * factor for digit, factor in zip(digits, factors)]
    total = sum(products)

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